<template>
  <div class="refund-management">
    <!-- 搜索筛选区域 -->
    <div class="card mb-4">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-search"></i> 查询条件
        </h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="handleSearch" class="row g-3">
          <div class="col-md-2">
            <label for="dateRange" class="form-label">日期范围</label>
            <select 
              class="form-select" 
              id="dateRange" 
              v-model="searchForm.dateRange"
              @change="handleDateRangeChange"
            >
              <option value="">全部</option>
              <option value="7">最近7天</option>
              <option value="15">最近15天</option>
              <option value="30">最近30天</option>
              <option value="60">最近60天</option>
              <option value="custom">自定义</option>
            </select>
          </div>
          <div class="col-md-2" v-if="searchForm.dateRange === 'custom'">
            <label for="startDate" class="form-label">开始日期</label>
            <input 
              type="date" 
              class="form-control" 
              id="startDate" 
              v-model="searchForm.startDate"
            >
          </div>
          <div class="col-md-2" v-if="searchForm.dateRange === 'custom'">
            <label for="endDate" class="form-label">结束日期</label>
            <input 
              type="date" 
              class="form-control" 
              id="endDate" 
              v-model="searchForm.endDate"
            >
          </div>
          <div class="col-md-2">
            <label for="patName" class="form-label">就诊人姓名</label>
            <input 
              type="text" 
              class="form-control" 
              id="patName" 
              v-model="searchForm.patName"
              placeholder="请输入就诊人姓名"
            >
          </div>
          <div class="col-md-2">
            <label for="patientId" class="form-label">就诊人卡号</label>
            <input 
              type="text" 
              class="form-control" 
              id="patientId" 
              v-model="searchForm.patientId"
              placeholder="请输入就诊人卡号"
            >
          </div>
          <div class="col-md-2">
            <label for="auditResult" class="form-label">审核状态</label>
            <select 
              class="form-select" 
              id="auditResult" 
              v-model="searchForm.auditResult"
            >
              <option value="">全部状态</option>
              <option value="0">待审核</option>
              <option value="1">审核通过</option>
              <option value="2">审核失败</option>
            </select>
          </div>
          <div class="col-12">
            <button type="submit" class="btn btn-primary me-2" :disabled="loading">
              <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
              <i v-else class="bi bi-search me-2"></i>
              查询
            </button>
            <button type="button" class="btn btn-outline-secondary" @click="resetSearch">
              <i class="bi bi-arrow-clockwise me-2"></i>
              重置
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 数据表格区域 -->
    <div class="card">
      <div class="card-header d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center gap-2">
        <h5 class="card-title mb-0">
          <i class="bi bi-table"></i> 退款申请列表
        </h5>
        <div class="d-flex flex-wrap align-items-center gap-2">
          <span class="text-muted me-3">共 {{ totalCount }} 条记录</span>
          <button class="btn btn-outline-primary btn-sm" @click="handleRefresh">
            <i class="bi bi-arrow-clockwise"></i> 刷新
          </button>
        </div>
      </div>
      <div class="card-body">
        <!-- 分页组件 - 顶部 -->
        <div v-if="totalCount > 0" class="mb-4">
          <!-- 分页信息和设置 -->
          <div class="row align-items-center mb-3">
            <div class="col-md-6">
              <div class="d-flex align-items-center flex-wrap">
                <div class="text-muted me-3 mb-2 mb-md-0">
                  <i class="bi bi-info-circle me-1"></i>
                  显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, totalCount) }} 条，共 {{ totalCount }} 条记录
                </div>
                <div class="text-muted mb-2 mb-md-0">
                  <i class="bi bi-file-text me-1"></i>
                  第 {{ currentPage }} 页，共 {{ Math.ceil(totalCount / pageSize) }} 页
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="d-flex align-items-center justify-content-md-end flex-wrap">
                <!-- 每页显示条数选择 -->
                <div class="d-flex align-items-center me-3 mb-2 mb-md-0">
                  <span class="text-muted me-2">
                    <i class="bi bi-list-ul me-1"></i>
                    每页显示
                  </span>
                  <select 
                    class="form-select form-select-sm" 
                    style="width: auto; min-width: 80px;"
                    :value="pageSize"
                    @change="handlePageSizeChange(parseInt($event.target.value))"
                  >
                    <option value="10">10 条</option>
                    <option value="20">20 条</option>
                    <option value="50">50 条</option>
                    <option value="100">100 条</option>
                  </select>
                </div>
                
                <!-- 页面跳转 -->
                <div class="d-flex align-items-center mb-2 mb-md-0" v-if="Math.ceil(totalCount / pageSize) > 1">
                  <span class="text-muted me-2">
                    <i class="bi bi-skip-end me-1"></i>
                    跳转到
                  </span>
                  <input 
                    type="number" 
                    class="form-control form-control-sm me-2" 
                    style="width: 70px;"
                    v-model="jumpToPage"
                    :placeholder="'1-' + Math.ceil(totalCount / pageSize)"
                    min="1"
                    :max="Math.ceil(totalCount / pageSize)"
                    @keyup.enter="handleJumpToPage"
                  >
                  <span class="text-muted me-2">页</span>
                  <button 
                    class="btn btn-outline-primary btn-sm" 
                    @click="handleJumpToPage"
                    :disabled="!jumpToPage"
                    title="跳转到指定页面"
                  >
                    <i class="bi bi-arrow-right"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页导航 -->
          <div v-if="Math.ceil(totalCount / pageSize) > 1" class="d-flex justify-content-center mb-3">
            <nav aria-label="分页导航">
              <ul class="pagination mb-0">
                <!-- 首页 -->
                <li class="page-item" :class="{ disabled: currentPage === 1 }">
                  <button 
                    class="page-link" 
                    @click="handlePageChange(1)" 
                    :disabled="currentPage === 1"
                    title="首页"
                  >
                    <i class="bi bi-chevron-double-left"></i>
                  </button>
                </li>
                
                <!-- 上一页 -->
                <li class="page-item" :class="{ disabled: currentPage === 1 }">
                  <button 
                    class="page-link" 
                    @click="handlePageChange(currentPage - 1)" 
                    :disabled="currentPage === 1"
                    title="上一页"
                  >
                    <i class="bi bi-chevron-left"></i>
                  </button>
                </li>
                
                <!-- 页码 -->
                <li v-for="page in getPageNumbers()" :key="page" class="page-item" :class="{ active: page === currentPage }">
                  <button class="page-link" @click="handlePageChange(page)" :title="'第' + page + '页'">{{ page }}</button>
                </li>
                
                <!-- 下一页 -->
                <li class="page-item" :class="{ disabled: currentPage === Math.ceil(totalCount / pageSize) }">
                  <button 
                    class="page-link" 
                    @click="handlePageChange(currentPage + 1)" 
                    :disabled="currentPage === Math.ceil(totalCount / pageSize)"
                    title="下一页"
                  >
                    <i class="bi bi-chevron-right"></i>
                  </button>
                </li>
                
                <!-- 末页 -->
                <li class="page-item" :class="{ disabled: currentPage === Math.ceil(totalCount / pageSize) }">
                  <button 
                    class="page-link" 
                    @click="handlePageChange(Math.ceil(totalCount / pageSize))" 
                    :disabled="currentPage === Math.ceil(totalCount / pageSize)"
                    title="末页"
                  >
                    <i class="bi bi-chevron-double-right"></i>
                  </button>
                </li>
              </ul>
            </nav>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2 text-muted">正在加载数据...</p>
        </div>

        <!-- 数据表格 -->
        <div v-else-if="refundList.length > 0" class="table-responsive-wrapper">
          <div class="table-responsive">
            <table class="table table-hover table-nowrap">
            <thead class="table-light">
              <tr>
                <th>申请ID</th>
                <th>申请日期</th>
                <th>就诊人信息</th>
                <th>申请类型</th>
                <th>代办人信息</th>
                <th>申请退款金额</th>
                <th>退款流水号</th>
                <th>附件</th>
                <th>审核状态</th>
                <th>审核人</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in refundList" :key="item.id">
                <td>{{ item.id }}</td>
                <td>{{ formatDate(item.inputDate) }}</td>
                <td>
                  <div class="small">
                    <div><strong>姓名: {{ item.patName }}</strong></div>
                    <div class="text-muted">卡号: {{ item.patientId }}</div>
                    <div class="text-muted">电话: {{ item.phoneNumber }}</div>
                  </div>
                </td>
                <td>
                  <span :class="getRefundTypeClass(item.refundTypeId)">
                    {{ item.refundTypeName || '本人退费' }}
                  </span>
                </td>
                <td>
                  <div v-if="item.refundTypeId === '5' && item.publicAgentName" class="small">
                    <div><strong>代办人: {{ item.publicAgentName }}</strong></div>
                    <div class="text-muted">关系: {{ item.publicAgentRelation }}</div>
                    <div class="text-muted">电话: {{ item.publicAgentPhoneNumber }}</div>
                  </div>
                  <span v-else class="text-muted">-</span>
                </td>
                <td class="text-start">
                  <div v-if="item.refundBalance && item.auditResult === '1'">
                    <div class="refund-amount-large text-success">实际退款: <span class="amount-highlight">¥{{ formatAmount(item.refundBalance) }}</span></div>
                    <div class="refund-amount-large text-danger">申请退款: <span class="amount-highlight">¥{{ formatAmount(item.refundAmount) }}</span></div>
                  </div>
                  <div v-else>
                    <div class="refund-amount-large text-danger">申请退款: <span class="amount-highlight">¥{{ formatAmount(item.refundAmount) }}</span></div>
                  </div>
                </td>
                <td>
                  <div v-if="item.refundBalanceSn" class="small">
                    <span class="text-primary fw-bold">{{ item.refundBalanceSn }}</span>
                  </div>
                  <span v-else class="text-muted small">-</span>
                </td>
                <td>
                  <div v-if="item.attachments && item.attachments.length > 0">
                    <button 
                      class="btn btn-outline-info btn-sm"
                      @click="previewAttachments(item)"
                      title="查看附件"
                    >
                      <i class="bi bi-paperclip"></i>
                      {{ item.attachments.length }}个附件
                    </button>
                  </div>
                  <span v-else class="text-muted small">无附件</span>
                </td>
                <td>
                  <span :class="getStatusClass(item.auditResult)">{{ getStatusText(item.auditResult) }}</span>
                  <div v-if="item.auditDate" class="small text-muted">
                    {{ formatDate(item.auditDate) }}
                  </div>
                </td>
                <td>
                  <div v-if="item.auditUserName" class="small">
                    {{ item.auditUserName }}
                  </div>
                  <span v-else class="text-muted">-</span>
                </td>
                <td>
                  <div class="btn-group btn-group-sm action-buttons-container">
                    <button 
                      class="btn btn-outline-primary action-btn action-btn-view" 
                      @click="viewDetail(item)"
                      title="查看详情"
                    >
                      <i class="bi bi-eye action-icon"></i>
                    </button>
                    <button 
                      v-if="!item.auditResult || item.auditResult === '0'" 
                      class="btn btn-outline-success action-btn action-btn-approve" 
                      @click="openAuditModal(item, '1')"
                      title="审核通过"
                    >
                      <i class="bi bi-check-lg action-icon"></i>
                    </button>
                    <button 
                      v-if="!item.auditResult || item.auditResult === '0'" 
                      class="btn btn-outline-danger action-btn action-btn-reject" 
                      @click="openAuditModal(item, '2')"
                      title="审核失败"
                    >
                      <i class="bi bi-x-lg action-icon"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
          </div>
          
        </div>
        
        <!-- 汇总统计卡片 - 按审核状态分类显示 -->
        <div v-if="refundList.length > 0" class="card mb-4 summary-card">
          <div class="card-header bg-light">
            <h6 class="mb-0">
              <i class="bi bi-bar-chart-fill text-primary me-2"></i>
              当前页数据汇总统计
            </h6>
          </div>
          <div class="card-body">
            <!-- 待审核统计 -->
            <div class="row mb-3" v-if="currentPagePendingCount > 0">
              <div class="col-12">
                <h6 class="text-warning mb-2">
                  <i class="bi bi-clock-fill me-1"></i>
                  待审核 ({{ currentPagePendingCount }} 条)
                </h6>
              </div>
              <div class="col-md-6 col-sm-6 mb-2">
                <div class="summary-item">
                  <div class="summary-label text-muted">申请退款金额</div>
                  <div class="summary-value text-warning">
                    <i class="bi bi-currency-yen me-1"></i>
                    ¥{{ formatAmount(currentPagePendingTotal) }}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 审核通过统计 -->
            <div class="row mb-3" v-if="currentPageApprovedCount > 0">
              <div class="col-12">
                <h6 class="text-success mb-2">
                  <i class="bi bi-check-circle-fill me-1"></i>
                  审核通过 ({{ currentPageApprovedCount }} 条)
                </h6>
              </div>
              <div class="col-md-6 col-sm-6 mb-2">
                <div class="summary-item">
                  <div class="summary-label text-muted">申请退款金额</div>
                  <div class="summary-value text-info">
                    <i class="bi bi-currency-yen me-1"></i>
                    ¥{{ formatAmount(currentPageApprovedApplyTotal) }}
                  </div>
                </div>
              </div>
              <div class="col-md-6 col-sm-6 mb-2">
                <div class="summary-item">
                  <div class="summary-label text-muted">实际退款金额</div>
                  <div class="summary-value text-success">
                    <i class="bi bi-currency-yen me-1"></i>
                    ¥{{ formatAmount(currentPageApprovedActualTotal) }}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 审核失败统计 -->
            <div class="row mb-3" v-if="currentPageRejectedCount > 0">
              <div class="col-12">
                <h6 class="text-danger mb-2">
                  <i class="bi bi-x-circle-fill me-1"></i>
                  审核失败 ({{ currentPageRejectedCount }} 条)
                </h6>
              </div>
              <div class="col-md-6 col-sm-6 mb-2">
                <div class="summary-item">
                  <div class="summary-label text-muted">申请退款金额</div>
                  <div class="summary-value text-danger">
                    <i class="bi bi-currency-yen me-1"></i>
                    ¥{{ formatAmount(currentPageRejectedTotal) }}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 总计统计 -->
            <div class="row border-top pt-3">
              <div class="col-12">
                <h6 class="text-primary mb-2">
                  <i class="bi bi-calculator-fill me-1"></i>
                  总计 ({{ refundList.length }} 条)
                </h6>
              </div>
              <div class="col-md-6 col-sm-6 mb-2">
                <div class="summary-item">
                  <div class="summary-label text-muted">申请退款总金额</div>
                  <div class="summary-value text-primary">
                    <i class="bi bi-currency-yen me-1"></i>
                    ¥{{ formatAmount(currentPageApplyTotal) }}
                  </div>
                </div>
              </div>
              <div class="col-md-6 col-sm-6 mb-2">
                <div class="summary-item">
                  <div class="summary-label text-muted">实际退款总金额</div>
                  <div class="summary-value text-success">
                    <i class="bi bi-currency-yen me-1"></i>
                    ¥{{ formatAmount(currentPageActualTotal) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="text-center py-5">
          <i class="bi bi-inbox display-1 text-muted"></i>
          <p class="mt-3 text-muted">暂无退款申请数据</p>
          <button class="btn btn-outline-primary" @click="handleRefresh">
            <i class="bi bi-arrow-clockwise me-2"></i>重新加载
          </button>
        </div>
      </div>
    </div>

    <!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1">
      <div class="modal-dialog modal-xl">
        <div class="modal-content detail-modal-content">
          <div class="modal-header detail-modal-header">
            <h4 class="modal-title detail-modal-title">
              <div class="title-icon-wrapper">
                <i class="bi bi-file-text-fill title-icon"></i>
              </div>
              <span class="title-text">退款申请详情</span>
              <div class="title-decoration"></div>
            </h4>
            <button type="button" class="btn-close detail-close-btn" @click="handleModalClose"></button>
          </div>
          <div class="modal-body detail-modal-body" v-if="selectedItem">
            <!-- 基本信息 -->
            <div class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-person-fill text-primary me-2"></i>
                  就诊人信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>申请ID：</strong>{{ selectedItem?.id }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>申请日期：</strong>{{ formatDate(selectedItem?.inputDate) }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>就诊人姓名：</strong>{{ selectedItem?.patName }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>就诊人卡号：</strong>{{ selectedItem?.patientId }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>身份证号：</strong>{{ selectedItem?.idNumber || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>联系电话：</strong>{{ selectedItem?.phoneNumber || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>申请退款金额：</strong>
                    <span v-if="selectedItem?.refundBalance && selectedItem?.auditResult === '1'" class="text-success">
                      实际退款 ¥{{ formatAmount(selectedItem?.refundBalance) }}
                      <small class="text-muted">(申请 ¥{{ formatAmount(selectedItem?.refundAmount) }})</small>
                    </span>
                    <span v-else class="text-primary">
                      ¥{{ formatAmount(selectedItem?.refundAmount) }}
                    </span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>HIS系统余额：</strong>
                    <span v-if="detailPatientBalanceLoading" class="text-muted">
                      <span class="spinner-border spinner-border-sm me-1"></span>获取中...
                    </span>
                    <span v-else-if="detailPatientBalance !== null" class="text-success">
                      ¥{{ formatAmount(detailPatientBalance) }}
                    </span>
                    <span v-else-if="detailPatientBalanceError" class="text-danger">
                      {{ detailPatientBalanceError }}
                    </span>
                    <span v-else class="text-muted">-</span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>申请类型：</strong>
                    <span class="badge" :class="getRefundTypeClass(selectedItem?.refundTypeId)">{{ selectedItem?.refundTypeName || '本人退费' }}</span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>退款流水号：</strong>
                    <span v-if="selectedItem?.refundBalanceSn">{{ selectedItem?.refundBalanceSn }}</span>
                      <span v-else class="muted-text">-</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 银行信息 -->
            <div class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-bank text-success me-2"></i>
                  {{ selectedItem?.refundTypeId === '5' ? '代办人银行信息' : '退款银行信息' }}
                  <span v-if="bankValidation.isValid" class="badge bg-success ms-2">
                    <i class="fas fa-check-circle me-1"></i>已验证
                  </span>
                  <span v-else-if="bankValidation.errors.length > 0" class="badge bg-warning ms-2">
                    <i class="fas fa-exclamation-triangle me-1"></i>需验证
                  </span>
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>开户银行：</strong>
                    <span>{{ selectedItem?.refundTypeId === '5' ? (selectedItem?.publicAgentRefundBankName || '-') : (selectedItem?.refundBankName || '-') }}</span>
                    <!-- 银行名称验证状态 -->
                    <span v-if="selectedItem?.refundTypeId === '5' ? selectedItem?.publicAgentRefundBankName : selectedItem?.refundBankName" class="ms-2">
                      <i v-if="bankValidation.bankNameValid" class="fas fa-check-circle text-success" title="银行名称有效"></i>
                      <i v-else class="fas fa-exclamation-circle text-warning" title="银行名称需要验证"></i>
                    </span>
                    <span v-if="bankValidation.standardizedBankName && bankValidation.standardizedBankName !== (selectedItem?.refundTypeId === '5' ? selectedItem?.publicAgentRefundBankName : selectedItem?.refundBankName)" class="text-muted small">
                      <br><i class="fas fa-arrow-right me-1"></i>标准化为：{{ bankValidation.standardizedBankName }}
                    </span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>银行卡号：</strong>
                    <span>{{ selectedItem?.refundTypeId === '5' ? (selectedItem?.publicAgentRefundBankCardNo || '-') : (selectedItem?.refundBankCardNo || '-') }}</span>
                    <!-- 银行卡号验证状态 -->
                    <span v-if="selectedItem?.refundTypeId === '5' ? selectedItem?.publicAgentRefundBankCardNo : selectedItem?.refundBankCardNo" class="ms-2">
                      <i v-if="bankValidation.cardNumberValid" class="fas fa-check-circle text-success" title="银行卡号格式正确"></i>
                      <i v-else class="fas fa-exclamation-circle text-warning" title="银行卡号格式需要验证"></i>
                    </span>
                    <span v-if="bankValidation.detectedBank" class="text-info small">
                      <br><i class="fas fa-info-circle me-1"></i>识别为：{{ bankValidation.detectedBank }}
                    </span>
                    <!-- 银行匹配状态 -->
                    <span v-if="(selectedItem?.refundTypeId === '5' ? selectedItem?.publicAgentRefundBankCardNo && selectedItem?.publicAgentRefundBankName : selectedItem?.refundBankCardNo && selectedItem?.refundBankName)" class="small">
                      <br>
                      <span v-if="bankValidation.bankMatch" class="text-success">
                        <i class="fas fa-check-circle me-1"></i>银行信息匹配
                      </span>
                      <span v-else-if="bankValidation.detectedBank && !bankValidation.bankMatch" class="text-warning">
                        <i class="fas fa-exclamation-triangle me-1"></i>银行信息不匹配
                      </span>
                    </span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>开户行名称：</strong>{{ selectedItem?.refundTypeId === '5' ? (selectedItem?.publicAgentRefundBankOpenName || '-') : (selectedItem?.refundBankOpenName || '-') }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>开户行城市：</strong>{{ selectedItem?.refundTypeId === '5' ? (selectedItem?.publicAgentRefundBankCity || '-') : (selectedItem?.refundBankCity || '-') }}
                  </div>
                </div>
                
                <!-- 银行卡验证结果 -->
                <div v-if="bankValidation.errors.length > 0" class="alert alert-warning mt-3">
                  <div class="d-flex align-items-center mb-2">
                    <i class="fas fa-exclamation-triangle text-warning me-2"></i>
                    <strong>银行卡信息验证提醒</strong>
                  </div>
                  <ul class="mb-0">
                    <li v-for="error in bankValidation.errors" :key="error" class="small">
                      {{ error }}
                    </li>
                  </ul>
                </div>
                
                <div v-else-if="bankValidation.isValid" class="alert alert-success mt-3">
                  <div class="d-flex align-items-center">
                    <i class="fas fa-check-circle text-success me-2"></i>
                    <strong>银行卡信息验证通过</strong>
                    <div class="ms-auto">
                      <span class="badge bg-success me-1">卡号格式正确</span>
                      <span class="badge bg-success me-1">银行名称有效</span>
                      <span v-if="bankValidation.bankMatch" class="badge bg-success">银行匹配</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 代办人信息 -->
            <div v-if="selectedItem?.refundTypeId === '5'" class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-people-fill text-info me-2"></i>
                  代办人信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>代办人姓名：</strong>{{ selectedItem?.publicAgentName || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>与患者关系：</strong>{{ selectedItem?.publicAgentRelation || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>代办人电话：</strong>{{ selectedItem?.publicAgentPhoneNumber || '-' }}
                  </div>
                </div>
              </div>
            </div>



            <!-- 审核信息 -->
            <div class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-clipboard-check-fill text-warning me-2"></i>
                  审核信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <strong>审核状态：</strong>
                    <span class="badge" :class="getStatusClass(selectedItem?.auditResult)">{{ getStatusText(selectedItem?.auditResult) }}</span>
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>审核人：</strong>{{ selectedItem?.auditUserName || '-' }}
                  </div>
                  <div class="col-md-6 mb-3">
                    <strong>审核时间：</strong>{{ selectedItem?.auditDate ? formatDate(selectedItem?.auditDate) : '-' }}
                  </div>
                  <div class="col-12 mb-3" v-if="selectedItem?.auditComment">
                    <strong>审核备注：</strong>{{ selectedItem?.auditComment }}
                  </div>
                  <div class="col-12 mb-3" v-if="!selectedItem?.auditResult || selectedItem?.auditResult === '0'">
                    <div class="d-flex justify-content-between align-items-center">
                      <strong>审核操作：</strong>
                      <div>
                        <button 
                          class="btn btn-success me-2" 
                          @click="openAuditModal(selectedItem, '1')"
                          title="审核通过"
                        >
                          <i class="bi bi-check-lg me-1"></i>
                          审核通过
                        </button>
                        <button 
                          class="btn btn-danger" 
                          @click="openAuditModal(selectedItem, '2')"
                          title="审核失败"
                        >
                          <i class="bi bi-x-lg me-1"></i>
                          审核失败
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 附件信息 -->
            <div v-if="selectedItem?.attachments && selectedItem?.attachments.length > 0" class="card mb-3">
              <div class="card-header bg-light">
                <h6 class="mb-0">
                  <i class="bi bi-paperclip text-secondary me-2"></i>
                  附件信息
                </h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div v-for="attachment in selectedItem?.attachments" :key="attachment.id" class="col-md-4 col-sm-6 mb-3">
                    <div class="card h-100">
                      <div class="card-body text-center">
                        <div class="mb-3" style="height: 120px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa; border-radius: 8px; cursor: pointer;" @click="previewImage(attachment)">
                          <!-- 加载状态 -->
                          <div v-if="thumbnailLoading[attachment.id]" class="text-muted">
                            <div class="spinner-border spinner-border-sm me-2"></div>
                            加载中...
                          </div>
                          <!-- 缩略图 -->
                          <img 
                            v-else-if="thumbnailUrls[attachment.id]"
                            :src="thumbnailUrls[attachment.id]"
                            class="img-fluid"
                            style="max-height: 100px; max-width: 100%;"
                            @error="handleThumbnailError(attachment.id)"
                            :alt="attachment.attachName"
                          >
                          <!-- 加载失败或默认图标 -->
                          <div v-else class="text-muted">
                            <i class="bi bi-file-earmark-image" style="font-size: 2rem;"></i>
                            <div class="small mt-1">点击预览</div>
                          </div>
                        </div>
                        <h6 class="card-title small" :title="attachment.attachName">{{ attachment.attachName }}</h6>
                        <button 
                          class="btn btn-outline-primary btn-sm"
                          @click="previewImage(attachment)"
                        >
                          <i class="bi bi-eye me-1"></i>
                          查看大图
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>

    <!-- 审核模态框 -->
    <div class="modal fade" id="auditModal" tabindex="-1">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header" :class="auditForm.result === '1' ? 'bg-success text-white' : 'bg-danger text-white'">
            <h5 class="modal-title">
              <i :class="auditForm.result === '1' ? 'bi bi-check-circle-fill me-2' : 'bi bi-x-circle-fill me-2'"></i>
              {{ auditForm.result === '1' ? '审核通过' : '审核失败' }}
            </h5>
            <button type="button" class="btn-close btn-close-white" @click="handleAuditModalClose"></button>
          </div>
          <div class="modal-body">
            <div class="mb-4">
              <h6 class="mb-3">
                <i class="bi bi-info-circle-fill text-primary me-2"></i>
                申请信息
              </h6>
              <div class="card">
                <div class="card-body">
                  <div class="row">
                    <div class="col-6 mb-2">
                      <strong>申请ID：</strong>{{ auditForm.refundItem?.id }}
                    </div>
                    <div class="col-6 mb-2">
                      <strong>就诊人：</strong>{{ auditForm.refundItem?.patName }}
                    </div>
                    <div class="col-6 mb-2">
                      <strong>患者卡号：</strong>{{ auditForm.refundItem?.patientId }}
                    </div>
                    <div class="col-6 mb-2">
                      <strong>申请退款金额：</strong><span class="text-danger fw-bold">¥{{ formatAmount(auditForm.refundItem?.refundAmount) }}</span>
                    </div>
                    <!-- 患者余额显示 -->
                    <div v-if="auditForm.result === '1'" class="col-12">
                      <strong>当前就诊卡余额：</strong>
                      <div v-if="patientBalanceLoading" class="text-muted">
                        <div class="spinner-border spinner-border-sm me-2"></div>
                        获取中...
                      </div>
                      <span v-else-if="patientBalance !== null" class="text-success fw-bold">
                        ¥{{ formatAmount(patientBalance) }}
                      </span>
                      <span v-else-if="patientBalanceError" class="text-danger">
                        {{ patientBalanceError }}
                      </span>
                      <!-- 余额不一致警告 -->
                      <div v-if="patientBalance !== null && patientBalance !== auditForm.refundItem?.refundAmount" class="alert alert-warning mt-2 mb-0">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        <strong>警告：</strong>申请退款金额（¥{{ formatAmount(auditForm.refundItem?.refundAmount) }}）与HIS系统余额（¥{{ formatAmount(patientBalance) }}）不一致，无法审核通过！
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 实际退款金额输入 -->
            <div v-if="auditForm.result === '1'" class="mb-4">
              <h6 class="mb-3">
                <i class="bi bi-currency-dollar text-success me-2"></i>
                退款金额设置
              </h6>
              <div class="card">
                <div class="card-body">
                  <div class="mb-3">
                    <small class="text-muted">申请退款金额：¥{{ formatAmount(auditForm.refundItem?.refundAmount) }}</small>
                  </div>
                  <div class="mb-3">
                    <label for="refundBalance" class="form-label">
                      实际退款金额 <span class="text-danger">*</span>
                    </label>
                    <div class="input-group">
                      <span class="input-group-text">¥</span>
                      <input 
                        type="text" 
                        class="form-control" 
                        id="refundBalance" 
                        v-model="auditForm.refundBalance"
                        placeholder="请输入实际退款金额"
                        :class="{ 'is-invalid': auditForm.showError && (!auditForm.refundBalance || auditForm.refundBalance <= 0) }"
                        disabled
                      >
                    </div>
                    <div v-if="auditForm.showError && (!auditForm.refundBalance || auditForm.refundBalance <= 0)" class="invalid-feedback d-block">
                      实际退款金额为必填项且必须大于0
                    </div>
                    <div class="form-text">
                      <i class="bi bi-info-circle me-1"></i>
                      实际退款金额不能超过HIS余额 ¥{{ formatAmount(patientBalance) }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="mb-4">
              <h6 class="mb-3">
                <i class="bi bi-chat-text-fill text-info me-2"></i>
                审核备注
              </h6>
              <div class="card">
                <div class="card-body">
                  <div class="mb-3">
                    <label class="form-label">常用备注</label>
                    <select 
                      class="form-select" 
                      v-model="auditForm.selectedDictComment"
                      @change="handleDictCommentChange"
                    >
                      <option value="">选择常用备注</option>
                      <option v-for="dict in auditDictList" :key="dict.id" :value="dict.itemName">
                        {{ dict.itemName }}
                      </option>
                    </select>
                  </div>
                  <div class="mb-3">
                    <label for="auditComment" class="form-label">
                      审核备注 <span class="text-danger">*</span>
                    </label>
                    <textarea 
                      class="form-control" 
                      id="auditComment" 
                      v-model="auditForm.comment"
                      rows="4"
                      placeholder="请输入审核备注（必填）"
                      :class="{ 'is-invalid': auditForm.showError && !auditForm.comment.trim() }"
                    ></textarea>
                    <div v-if="auditForm.showError && !auditForm.comment.trim()" class="invalid-feedback">
                      审核备注为必填项
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
              <i class="bi bi-x-circle me-2"></i>
              取消
            </button>
            <!-- 等待HIS退费按钮 - 仅在审核通过时显示 -->
            <button 
              v-if="auditForm.result === '1'"
              type="button" 
              class="btn btn-warning me-2"
              @click="waitForHisRefund"
              :disabled="auditForm.waitingHisRefund || auditLoading || (patientBalance !== null && (patientBalance <= 0 || patientBalance !== auditForm.refundItem?.refundAmount))"
              :title="(patientBalance !== null && patientBalance <= 0) ? 'HIS系统余额为0，无需退费' : (patientBalance !== null && patientBalance !== auditForm.refundItem?.refundAmount) ? '申请退款金额与HIS余额不一致，无法退费' : ''"
            >
              <span v-if="auditForm.waitingHisRefund" class="spinner-border spinner-border-sm me-2"></span>
              <i v-else class="bi bi-clock me-2"></i>
              等待HIS退费
            </button>
            <!-- 确认通过/失败按钮 -->
            <button 
              type="button" 
              class="btn" 
              :class="auditForm.result === '1' ? 'btn-success' : 'btn-danger'"
              @click="submitAudit"
              :disabled="auditLoading || (auditForm.result === '1' && !auditForm.waitingHisRefund) || (auditForm.result === '1' && patientBalance !== null && (patientBalance <= 0 || patientBalance !== auditForm.refundItem?.refundAmount))"
              :title="(auditForm.result === '1' && patientBalance !== null && patientBalance <= 0) ? 'HIS系统余额为0，无法确认通过' : (auditForm.result === '1' && patientBalance !== null && patientBalance !== auditForm.refundItem?.refundAmount) ? '申请退款金额与HIS余额不一致，无法确认通过' : ''"
              @mouseenter="console.log('按钮状态检查:', {
                auditLoading: auditLoading,
                result: auditForm.result,
                waitingHisRefund: auditForm.waitingHisRefund,
                patientBalance: patientBalance,
                refundAmount: auditForm.refundItem?.refundAmount,
                disabled: auditLoading || (auditForm.result === '1' && !auditForm.waitingHisRefund) || (auditForm.result === '1' && patientBalance !== null && (patientBalance <= 0 || patientBalance !== auditForm.refundItem?.refundAmount))
              })"
            >
              <span v-if="auditLoading" class="spinner-border spinner-border-sm me-2"></span>
              <i v-else :class="auditForm.result === '1' ? 'bi bi-check-lg' : 'bi bi-x-lg'" class="me-2"></i>
              确认{{ auditForm.result === '1' ? '通过' : '失败' }}
            </button>
            <!-- 倒计时显示 -->
            <div v-if="auditForm.preventPageLeave && auditForm.remainingTime > 0" class="alert alert-warning mt-2 mb-0">
              <i class="bi bi-exclamation-triangle me-2"></i>
              <strong>页面锁定中：</strong>剩余时间 {{ formatRemainingTime(auditForm.remainingTime) }}，期间不能刷新或关闭页面
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 附件预览模态框 -->
    <div class="modal fade" id="attachmentModal" tabindex="-1">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-paperclip"></i> 附件预览
              <span v-if="currentAttachments.length > 1" class="badge bg-secondary ms-2">
                {{ currentImageIndex + 1 }} / {{ currentAttachments.length }}
              </span>
            </h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <div v-if="previewAttachment" class="text-center position-relative">
              <h6>{{ previewAttachment.attachName }}</h6>
              <div class="mt-3 position-relative">
                <!-- 左侧导航箭头 -->
                <button 
                  v-if="currentAttachments.length > 1 && currentImageIndex > 0"
                  class="btn btn-dark btn-sm position-absolute start-0 top-50 translate-middle-y"
                  style="z-index: 10; opacity: 0.7;"
                  @click="previousImage"
                  @mouseover="$event.target.style.opacity = '1'"
                  @mouseleave="$event.target.style.opacity = '0.7'"
                >
                  <i class="bi bi-chevron-left"></i>
                </button>
                
                <!-- 右侧导航箭头 -->
                <button 
                  v-if="currentAttachments.length > 1 && currentImageIndex < currentAttachments.length - 1"
                  class="btn btn-dark btn-sm position-absolute end-0 top-50 translate-middle-y"
                  style="z-index: 10; opacity: 0.7;"
                  @click="nextImage"
                  @mouseover="$event.target.style.opacity = '1'"
                  @mouseleave="$event.target.style.opacity = '0.7'"
                >
                  <i class="bi bi-chevron-right"></i>
                </button>
                
                <!-- 加载状态 -->
                <div v-if="imageLoading" class="d-flex justify-content-center align-items-center" style="height: 300px;">
                  <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                  </div>
                  <span class="ms-2">正在加载图片...</span>
                </div>
                <!-- 图片显示 -->
                <div v-else-if="previewImageUrl">
                  <!-- 图片控制按钮 - 固定在顶部 -->
                  <div class="mb-3" style="position: sticky; top: 0; z-index: 10; background: white; padding: 10px 0; border-bottom: 1px solid #dee2e6;">
                    <!-- 操作提示 -->
                    <div class="text-center mb-2">
                      <small class="text-muted">
                        <i class="bi bi-info-circle me-1"></i>
                        点击图片选中后，可使用鼠标滚轮进行缩放
                        <span v-if="imageFocused" class="text-primary ms-2">
                          <i class="bi bi-check-circle-fill"></i> 已选中
                        </span>
                      </small>
                    </div>
                    <!-- 控制按钮 -->
                    <div class="d-flex justify-content-center gap-2">
                    <!-- 旋转控制 -->
                    <div class="btn-group me-2">
                      <button 
                        class="btn btn-outline-secondary btn-sm"
                        @click="rotateImage(-90)"
                        title="逆时针旋转90度"
                      >
                        <i class="bi bi-arrow-counterclockwise"></i> 逆时针
                      </button>
                      <button 
                        class="btn btn-outline-secondary btn-sm"
                        @click="rotateImage(90)"
                        title="顺时针旋转90度"
                      >
                        <i class="bi bi-arrow-clockwise"></i> 顺时针
                      </button>
                      <button 
                        class="btn btn-outline-secondary btn-sm"
                        @click="resetRotation"
                        title="重置旋转"
                      >
                        <i class="bi bi-arrow-repeat"></i> 重置
                      </button>
                    </div>
                    
                    <!-- 缩放控制 -->
                    <div class="btn-group">
                      <button 
                        class="btn btn-outline-primary btn-sm"
                        @click="zoomImage(0.1)"
                        title="放大图片"
                      >
                        <i class="bi bi-zoom-in"></i> 放大
                      </button>
                      <button 
                        class="btn btn-outline-primary btn-sm"
                        @click="zoomImage(-0.1)"
                        title="缩小图片"
                      >
                        <i class="bi bi-zoom-out"></i> 缩小
                      </button>
                      <button 
                        class="btn btn-outline-primary btn-sm"
                        @click="resetZoom"
                        title="重置缩放"
                      >
                        <i class="bi bi-aspect-ratio"></i> 重置
                      </button>
                    </div>
                     </div>
                  </div>
                  <!-- 图片容器 - 使用滚动容器 -->
                   <div 
                     style="max-height: 70vh; overflow: auto; display: flex; justify-content: center; align-items: center;"
                     @wheel="handleImageWheel"
                   >
                     <img 
                       :src="previewImageUrl"
                       class="img-fluid"
                       :style="{ 
                         maxWidth: 'none', 
                         height: 'auto',
                         transform: `translate(${imagePosition.x}px, ${imagePosition.y}px) rotate(${imageRotation}deg) scale(${imageScale})`, 
                         transition: isDragging ? 'none' : 'transform 0.3s ease',
                         display: 'block',
                         cursor: isDragging ? 'grabbing' : 'grab',
                         userSelect: 'none',
                         border: imageFocused ? '3px solid #0d6efd' : '3px solid transparent',
                         borderRadius: '8px',
                         boxShadow: imageFocused ? '0 0 15px rgba(13, 110, 253, 0.3)' : 'none'
                       }"
                       @error="handleImageError"
                       @mousedown="startDrag"
                       @mousemove="onDrag"
                       @mouseup="endDrag"
                       @mouseleave="endDrag"
                       @dragstart.prevent
                       @click="focusImage"
                       alt="附件预览"
                       ref="previewImageRef"
                     >
                   </div>
                </div>
                <!-- 加载失败 -->
                <div v-else class="d-flex justify-content-center align-items-center" style="height: 300px;">
                  <div class="text-muted">
                    <i class="bi bi-exclamation-triangle fs-1"></i>
                    <p class="mt-2">图片加载失败</p>
                  </div>
                </div>
              </div>
              
              <!-- 图片指示器 -->
              <div v-if="currentAttachments.length > 1" class="mt-3">
                <div class="d-flex justify-content-center gap-2">
                  <button 
                    v-for="(attachment, index) in currentAttachments" 
                    :key="attachment.id"
                    class="btn btn-sm"
                    :class="index === currentImageIndex ? 'btn-primary' : 'btn-outline-secondary'"
                    @click="goToImage(index)"
                    :title="attachment.attachName"
                  >
                    {{ index + 1 }}
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            <button 
              type="button" 
              class="btn btn-primary me-2"
              @click="downloadAttachment(previewAttachment)"
            >
              <i class="bi bi-download me-2"></i>下载
            </button>
            <button 
              type="button" 
              class="btn btn-success"
              @click="openPrintSettings"
            >
              <i class="bi bi-printer me-2"></i>打印
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 打印设置模态框 -->
    <div class="modal fade" id="printSettingsModal" tabindex="-1">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header bg-primary text-white">
            <h5 class="modal-title">
              <i class="bi bi-printer-fill me-2"></i>打印设置
            </h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <!-- 图片选择 -->
            <div class="mb-4">
              <h6 class="mb-3">
                <i class="bi bi-images text-primary me-2"></i>
                选择要打印的图片
              </h6>
              <div class="d-flex justify-content-between align-items-center mb-3">
                <span class="text-muted">已选择 {{ printSettings.selectedImages.size }} / {{ currentAttachments.length }} 张图片</span>
                <div>
                  <button type="button" class="btn btn-outline-primary btn-sm me-2" @click="selectAllImages">
                    <i class="bi bi-check-all me-1"></i>全选
                  </button>
                  <button type="button" class="btn btn-outline-secondary btn-sm" @click="deselectAllImages">
                    <i class="bi bi-x-circle me-1"></i>清空
                  </button>
                </div>
              </div>
              <div class="row g-3">
                <div v-for="(attachment, index) in currentAttachments" :key="attachment.id" class="col-md-4 col-sm-6">
                  <div class="card h-100" :class="{ 'border-primary': printSettings.selectedImages.has(index) }">
                    <div class="card-body text-center p-2">
                      <div class="form-check position-absolute top-0 start-0 m-2">
                        <input 
                          class="form-check-input" 
                          type="checkbox" 
                          :checked="printSettings.selectedImages.has(index)"
                          @change="toggleImageSelection(index)"
                          :id="'print-img-' + index"
                        >
                      </div>
                      <div class="mb-2" style="height: 80px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa; border-radius: 4px;">
                        <img 
                          v-if="thumbnailUrls[attachment.id]"
                          :src="thumbnailUrls[attachment.id]"
                          class="img-fluid"
                          style="max-height: 70px; max-width: 100%;"
                          :alt="attachment.attachName"
                        >
                        <i v-else class="bi bi-file-earmark-image text-muted" style="font-size: 1.5rem;"></i>
                      </div>
                      <h6 class="card-title small" :title="attachment.attachName">{{ attachment.attachName }}</h6>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 打印设置 -->
            <div class="row g-3">
              <div class="col-md-6">
                <label class="form-label">纸张大小</label>
                <select class="form-select" v-model="printSettings.paperSize">
                  <option value="A4">A4</option>
                  <option value="A3">A3</option>
                  <option value="Letter">Letter</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">打印方向</label>
                <select class="form-select" v-model="printSettings.orientation">
                  <option value="portrait">纵向</option>
                  <option value="landscape">横向</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">页边距 (mm)</label>
                <input type="number" class="form-control" v-model="printSettings.margin" min="0" max="50">
              </div>
              <div class="col-md-6">
                <label class="form-label">每页图片数量</label>
                <select class="form-select" v-model="printSettings.imagesPerPage">
                  <option value="1">1张/页</option>
                  <option value="2">2张/页</option>
                  <option value="4">4张/页</option>
                </select>
              </div>
              <div class="col-12">
                <div class="form-check">
                  <input class="form-check-input" type="checkbox" v-model="printSettings.fitToPage" id="fitToPage">
                  <label class="form-check-label" for="fitToPage">
                    适应页面大小
                  </label>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
              <i class="bi bi-x-circle me-2"></i>取消
            </button>
            <button 
              type="button" 
              class="btn btn-primary"
              @click="generatePrintPreview"
              :disabled="printSettings.selectedImages.size === 0 || printLoading"
            >
              <span v-if="printLoading" class="spinner-border spinner-border-sm me-2"></span>
              <i v-else class="bi bi-eye me-2"></i>
              生成预览
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 打印预览模态框 -->
    <div class="modal fade" id="printPreviewModal" tabindex="-1">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header bg-success text-white">
            <h5 class="modal-title">
              <i class="bi bi-file-earmark-text-fill me-2"></i>打印预览
            </h5>
            <button type="button" class="btn-close btn-close-white" @click="closePrintPreview"></button>
          </div>
          <div class="modal-body">
            <div class="text-center mb-3">
              <div class="d-flex justify-content-between align-items-center">
                <span class="text-muted">共 {{ printPreviewImages.length }} 张图片</span>
                <div>
                  <span class="badge bg-primary me-2">{{ printSettings.paperSize }}</span>
                  <span class="badge bg-info me-2">{{ printSettings.orientation === 'portrait' ? '纵向' : '横向' }}</span>
                  <span class="badge bg-secondary">{{ printSettings.imagesPerPage }}张/页</span>
                </div>
              </div>
            </div>
            
            <!-- 预览内容 -->
            <div class="print-preview-container" style="max-height: 60vh; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; background-color: #f8f9fa;">
              <div v-for="(image, index) in printPreviewImages" :key="index" class="preview-page mb-4">
                <div class="text-center mb-3">
                  <div class="preview-header p-3 bg-white border rounded">
                    <h6 class="mb-1">退款申请附件</h6>
                    <small class="text-muted">
                      申请ID: {{ selectedItem?.id }} | 就诊人: {{ selectedItem?.patName }}
                    </small>
                  </div>
                </div>
                <div class="text-center bg-white border rounded p-3">
                  <img 
                    :src="image.url" 
                    :alt="image.name" 
                    class="img-fluid"
                    style="max-width: 100%; max-height: 400px; object-fit: contain; border: 1px solid #ddd;"
                  >
                  <div class="mt-2">
                    <small class="text-muted">{{ image.name }}</small>
                  </div>
                </div>
                <hr v-if="index < printPreviewImages.length - 1" class="my-4">
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="closePrintPreview">
              <i class="bi bi-x-circle me-2"></i>关闭
            </button>
            <button type="button" class="btn btn-outline-primary me-2" data-bs-dismiss="modal" @click="openPrintSettings">
              <i class="bi bi-gear me-2"></i>修改设置
            </button>
            <button type="button" class="btn btn-success" @click="executePrint">
              <i class="bi bi-printer me-2"></i>开始打印
            </button>
          </div>
        </div>
      </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { Modal } from 'bootstrap'
import api from '@/utils/api'
import { useAuthStore } from '@/stores/auth'
import { validateBankCardEnhanced as validateBankCard } from '@/utils/enhancedBankCardValidator'
import CryptoJS from 'crypto-js'

// 响应式数据
const loading = ref(false)
const auditLoading = ref(false)
const refundList = ref([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const jumpToPage = ref('')
const selectedItem = ref(null)
const previewAttachment = ref(null)
const previewImageUrl = ref('')
const imageLoading = ref(false)
const currentAttachments = ref([])
const currentImageIndex = ref(0)
const imageRotation = ref(0) // 图片旋转角度
const imageScale = ref(1) // 图片缩放比例
const imagePosition = ref({ x: 0, y: 0 }) // 图片位置
const isDragging = ref(false) // 是否正在拖拽
const dragStart = ref({ x: 0, y: 0 }) // 拖拽开始位置
const imageFocused = ref(false) // 图片是否被选中/聚焦
const previewImageRef = ref(null) // 图片元素引用
const thumbnailUrls = ref({})
const thumbnailLoading = ref({})
const auditDictList = ref([])
// 患者余额相关状态
const patientBalance = ref(null)
const patientBalanceLoading = ref(false)
const patientBalanceError = ref('')
// 详情页面患者余额相关状态
const detailPatientBalance = ref(null)
const detailPatientBalanceLoading = ref(false)
const detailPatientBalanceError = ref('')
// 打印相关状态
const printSettings = ref({
  selectedImages: new Set(), // 选中的图片索引
  paperSize: 'A4', // 纸张大小
  orientation: 'portrait', // 打印方向：portrait(纵向) 或 landscape(横向)
  margin: '10', // 页边距(mm)
  imagesPerPage: 1, // 每页图片数量
  fitToPage: true, // 是否适应页面大小
  showPrintPreview: false // 是否显示打印预览
})
const printPreviewImages = ref([]) // 打印预览图片数据
const printLoading = ref(false) // 打印加载状态

// 当前页汇总统计计算属性
// 待审核申请金额
const currentPagePendingTotal = computed(() => {
  return refundList.value.reduce((total, item) => {
    if (!item.auditResult || item.auditResult === '0') {
      return total + (parseFloat(item.refundAmount) || 0)
    }
    return total
  }, 0)
})

// 审核通过申请金额
const currentPageApprovedApplyTotal = computed(() => {
  return refundList.value.reduce((total, item) => {
    if (item.auditResult === '1') {
      return total + (parseFloat(item.refundAmount) || 0)
    }
    return total
  }, 0)
})

// 审核通过实际退款金额
const currentPageApprovedActualTotal = computed(() => {
  return refundList.value.reduce((total, item) => {
    if (item.auditResult === '1' && item.refundBalance) {
      return total + (parseFloat(item.refundBalance) || 0)
    }
    return total
  }, 0)
})

// 审核失败申请金额
const currentPageRejectedTotal = computed(() => {
  return refundList.value.reduce((total, item) => {
    if (item.auditResult === '2') {
      return total + (parseFloat(item.refundAmount) || 0)
    }
    return total
  }, 0)
})

// 各状态记录数统计
const currentPagePendingCount = computed(() => {
  return refundList.value.filter(item => !item.auditResult || item.auditResult === '0').length
})

const currentPageApprovedCount = computed(() => {
  return refundList.value.filter(item => item.auditResult === '1').length
})

const currentPageRejectedCount = computed(() => {
  return refundList.value.filter(item => item.auditResult === '2').length
})

// 保留原有的总计算属性（如果其他地方还在使用）
const currentPageApplyTotal = computed(() => {
  return refundList.value.reduce((total, item) => {
    return total + (parseFloat(item.refundAmount) || 0)
  }, 0)
})

const currentPageActualTotal = computed(() => {
  return refundList.value.reduce((total, item) => {
    if (item.auditResult === '1' && item.refundBalance) {
      return total + (parseFloat(item.refundBalance) || 0)
    }
    return total
  }, 0)
})

// 银行卡验证相关状态
const bankValidation = ref({
  isValid: false,
  cardNumberValid: false,
  bankNameValid: false,
  bankMatch: false,
  detectedBank: null,
  standardizedBankName: null,
  errors: []
})

// 搜索表单
const searchForm = ref({
  dateRange: '',
  patientId: '',
  patName: '',
  auditResult: '',
  startDate: '',
  endDate: ''
})

// 审核表单
const auditForm = ref({
  refundItem: null,
  result: '',
  comment: '',
  selectedDictComment: '',
  refundBalance: null,
  showError: false,
  waitingHisRefund: false, // 新增：是否正在等待HIS退费
  preventPageLeave: false, // 新增：是否阻止页面离开
  countdownTimer: null, // 新增：倒计时定时器
  remainingTime: 0 // 新增：剩余时间（秒）
})

// 模态框实例
let detailModal = null
let auditModal = null
let attachmentModal = null
let printSettingsModal = null
let printPreviewModal = null

// 键盘事件处理
const handleKeydown = (event) => {
  // 只在附件预览模态框打开时处理键盘事件
  if (attachmentModal && document.getElementById('attachmentModal').classList.contains('show')) {
    if (event.key === 'ArrowLeft') {
      event.preventDefault()
      previousImage()
    } else if (event.key === 'ArrowRight') {
      event.preventDefault()
      nextImage()
    } else if (event.key === 'Escape') {
      event.preventDefault()
      attachmentModal.hide()
    }
  }
}

// 获取认证store
const authStore = useAuthStore()

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

// 获取状态样式类
const getStatusClass = (auditResult) => {
  const statusClasses = {
    '0': 'badge bg-warning text-dark status-badge-large',
    '1': 'badge bg-success status-badge-large',
    '2': 'badge bg-danger status-badge-large'
  }
  return statusClasses[auditResult] || 'badge bg-warning text-dark status-badge-large'
}

// 获取状态文本
const getStatusText = (auditResult) => {
  const statusTexts = {
    '0': '待审核',
    '1': '审核通过',
    '2': '审核失败'
  }
  return statusTexts[auditResult] || '待审核'
}

// 获取申请类型样式类
const getRefundTypeClass = (refundTypeId) => {
  const typeClasses = {
    '1': 'badge bg-primary type-badge-large',
    '2': 'badge bg-info type-badge-large'
  }
  return typeClasses[refundTypeId] || 'badge bg-primary type-badge-large'
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  if (searchForm.value.dateRange && searchForm.value.dateRange !== 'custom') {
    // 清空自定义日期
    searchForm.value.startDate = ''
    searchForm.value.endDate = ''
  }
}

// 加载退款申请列表
const loadRefundList = async () => {
  loading.value = true
  try {
    // 处理日期范围逻辑
    let startDate = null
    let endDate = null
    
    if (searchForm.value.dateRange === 'custom') {
      // 自定义日期范围
      startDate = searchForm.value.startDate || null
      endDate = searchForm.value.endDate || null
    } else if (searchForm.value.dateRange && searchForm.value.dateRange !== '') {
      // 预设日期范围
      const days = parseInt(searchForm.value.dateRange)
      const now = new Date()
      endDate = now.toISOString().split('T')[0] // 今天
      startDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0] // N天前
    }
    
    // 构建查询请求
    const queryRequest = {
      startDate: startDate,
      endDate: endDate,
      auditStatus: searchForm.value.auditResult !== '' ? parseInt(searchForm.value.auditResult) : null,
      patientId: searchForm.value.patientId || null,
      patientName: searchForm.value.patName || null,
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      defaultDays: 30 // 默认查询30天内的数据
    }
    
    // 使用新的带过滤条件的API
    const response = await api.post('/api/refund/get-with-filter', queryRequest)
    
    refundList.value = response.data.data || []
    totalCount.value = response.data.totalCount || 0
    
  } catch (error) {
    console.error('加载退款申请列表出错:', error)
    refundList.value = []
    totalCount.value = 0
    showToast('加载数据失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  loadRefundList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    dateRange: '',
    patientId: '',
    patName: '',
    auditResult: '',
    startDate: '',
    endDate: ''
  }
  currentPage.value = 1 // 重置到第一页
  loadRefundList()
}

// 刷新数据
const handleRefresh = () => {
  loadRefundList()
}

// 查看详情
const viewDetail = (item) => {
  selectedItem.value = item
  
  // 清空之前的缩略图数据
  thumbnailUrls.value = {}
  thumbnailLoading.value = {}
  
  // 重置详情页面患者余额状态
  detailPatientBalance.value = null
  detailPatientBalanceLoading.value = false
  detailPatientBalanceError.value = ''
  
  // 获取患者余额
  if (item.patientId) {
    getDetailPatientBalance(item.patientId)
  }
  
  // 显示模态框
  if (detailModal) {
    detailModal.show()
  }
  
  // 加载所有附件的缩略图
  if (item.attachments && item.attachments.length > 0) {
    item.attachments.forEach(attachment => {
      loadThumbnail(attachment)
    })
  }
}

// 获取患者余额
const getPatientBalance = async (patientId) => {
  if (!patientId) {
    patientBalanceError.value = '患者ID为空'
    return
  }
  
  patientBalanceLoading.value = true
  patientBalanceError.value = ''
  patientBalance.value = null
  console.log('开始获取患者余额...')
  
  try {
    // 修复：使用正确的GET方法和端点
    const response = await api.get(`/api/refund/patient-balance/${patientId}`)
    
    console.log('患者余额响应:', response.data)
    
    if (response.data && response.data.success) {
      patientBalance.value = response.data.data.balance
      console.log('设置 patientBalance:', patientBalance.value)
      
      // 重新计算按钮禁用状态
      const buttonDisabled = auditLoading.value || 
        (auditForm.value.result === '1' && !auditForm.value.waitingHisRefund) || 
        (auditForm.value.result === '1' && patientBalance.value !== null && patientBalance.value <= 0)
      
      console.log('余额获取后按钮禁用状态:', buttonDisabled)
      
      // 如果是审核通过状态，将实际退款金额默认设置为患者余额（但不超过申请金额）
      if (auditForm.value && auditForm.value.result === '1') {
        const maxAmount = auditForm.value.refundItem?.refundAmount || 0
        auditForm.value.refundBalance = Math.min(response.data.data.balance, maxAmount)
        console.log('设置实际退款金额:', auditForm.value.refundBalance)
      }
    } else {
      patientBalanceError.value = response.data?.message || '未获取到余额信息'
      console.log('获取余额失败:', patientBalanceError.value)
    }
  } catch (error) {
    console.error('获取患者余额失败:', error)
    patientBalanceError.value = error.response?.data?.message || '获取余额失败'
  } finally {
    patientBalanceLoading.value = false
    console.log('=== getPatientBalance 结束 ===')
  }
}

// 详情页面获取患者余额
const getDetailPatientBalance = async (patientId) => {
  if (!patientId) {
    detailPatientBalanceError.value = '患者ID为空'
    return
  }
  
  detailPatientBalanceLoading.value = true
  detailPatientBalanceError.value = ''
  detailPatientBalance.value = null
  
  try {
    const response = await api.get(`/api/refund/patient-balance/${patientId}`)
    // 处理新的API返回格式：{ success: true, data: { patientId, balance }, message }
    if (response.data && response.data.success && response.data.data && response.data.data.balance !== undefined) {
      detailPatientBalance.value = response.data.data.balance
    } else {
      detailPatientBalanceError.value = response.data?.message || '未获取到余额信息'
    }
  } catch (error) {
    console.error('获取患者余额失败:', error)
    detailPatientBalanceError.value = error.response?.data?.message || '获取余额失败'
  } finally {
    detailPatientBalanceLoading.value = false
  }
}

// 打开审核模态框
const openAuditModal = (item, result) => {
  console.log('=== openAuditModal 开始 ===')
  console.log('item:', item)
  console.log('result:', result)
  console.log('当前 auditLoading:', auditLoading.value)
  
  // 完全重置模态框状态
  const auditModalElement = document.getElementById('auditModal')
  if (auditModalElement) {
    // 确保模态框完全关闭
    auditModalElement.classList.remove('show')
    auditModalElement.style.display = 'none'
    auditModalElement.setAttribute('aria-hidden', 'true')
    auditModalElement.removeAttribute('aria-modal')
    auditModalElement.removeAttribute('data-bs-backdrop')
    auditModalElement.removeAttribute('data-bs-keyboard')
  }
  
  // 清理可能残留的 backdrop
  const backdrops = document.querySelectorAll('.modal-backdrop')
  backdrops.forEach(backdrop => backdrop.remove())
  
  // 重置 body 状态
  document.body.classList.remove('modal-open')
  document.body.style.overflow = ''
  document.body.style.paddingRight = ''
  
  // 重新初始化 Bootstrap Modal 实例
  if (auditModal) {
    auditModal.dispose() // 销毁现有实例
  }
  auditModal = new Modal(auditModalElement) // 重新创建实例
  
  // 重新添加事件监听器
  auditModalElement.addEventListener('hide.bs.modal', (event) => {
    if (auditForm.value.preventPageLeave) {
      event.preventDefault()
      showToast('正在等待HIS退费确认，不能关闭审核页面！', 'error')
    }
  })
  
  // 清除之前的定时器（如果存在）
  clearCountdownTimer()
  
  // 重置审核加载状态
  auditLoading.value = false
  console.log('重置后 auditLoading:', auditLoading.value)
  
  auditForm.value = {
    refundItem: item,
    result: result,
    comment: '',
    selectedDictComment: '',
    refundBalance: null, // 初始为null，等待从HIS获取患者余额后设置
    showError: false,
    waitingHisRefund: false, // 重置等待HIS退费状态
    preventPageLeave: false, // 确保重置为false
    countdownTimer: null, // 重置定时器
    remainingTime: 0 // 重置剩余时间
  }
  
  console.log('设置后 auditForm.waitingHisRefund:', auditForm.value.waitingHisRefund)
  console.log('设置后 auditForm.result:', auditForm.value.result)
  console.log('设置后 auditForm.preventPageLeave:', auditForm.value.preventPageLeave)
  
  // 重置患者余额状态
  patientBalance.value = null
  patientBalanceLoading.value = false
  patientBalanceError.value = ''
  console.log('重置后 patientBalance:', patientBalance.value)
  
  // 根据审核结果加载对应的字典数据
  // result === '1' 审核通过，使用dictId: 5
  // result === '2' 审核失败，使用dictId: 6
  const dictId = result === '1' ? 5 : 6
  loadAuditDict(dictId)
  
  // 如果是审核通过，获取患者余额
  if (result === '1' && item.patientId) {
    console.log('审核通过，开始获取患者余额...')
    getPatientBalance(item.patientId)
  }
  
  // 确保auditModal已初始化
  if (!auditModal) {
    if (auditModalElement) {
      auditModal = new Modal(auditModalElement)
    } else {
      console.error('auditModal element not found')
      return
    }
  }
  
  // 关闭详情模态框
  if (detailModal) {
    detailModal.hide()
  }
  
  // 在函数最后显示模态框时，添加延迟确保状态完全重置
  console.log('尝试显示审核模态框...')
  setTimeout(() => {
    if (auditModal) {
      auditModal.show()
      console.log('审核模态框显示成功')
    }
  }, 100) // 添加100ms延迟
  
  console.log('=== openAuditModal 结束 ===')
}

// 处理字典备注选择
const handleDictCommentChange = () => {
  if (auditForm.value.selectedDictComment) {
    auditForm.value.comment = auditForm.value.selectedDictComment
  }
}

// 生成MD5哈希（前端实现）
const generateMD5 = async (text) => {
  try {
    // 使用crypto-js在前端生成MD5
    const hash = CryptoJS.MD5(text).toString()
    console.log('前端MD5加密完成:', text, '->', hash)
    return hash
  } catch (error) {
    console.error('前端MD5生成失败:', error)
    throw error
  }
}

// 生成6位随机数
const generateRandomCode = () => {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

// 等待HIS退费
const waitForHisRefund = async () => {
  console.log('=== waitForHisRefund 开始 ===')
  console.log('当前 patientBalance:', patientBalance.value)
  
  // 检查HIS系统余额是否为0
  if (patientBalance.value !== null && patientBalance.value <= 0) {
    console.log('HIS系统余额为0，无需退费操作')
    showToast('HIS系统余额为0，无需退费操作', 'error')
    return
  }
  
  try {
    console.log('开始HIS退费流程...')
    
    // 生成6位随机数
    const randomCode = generateRandomCode()
    console.log('生成随机码:', randomCode)
    
    // MD5加密
    const encryptedPassword = await generateMD5(randomCode)
    console.log('MD5加密完成')
    
    // 获取当前用户信息
    const userInfo = authStore.user
    if (!userInfo) {
      console.log('获取用户信息失败')
      showToast('获取用户信息失败，请重新登录', 'error')
      return
    }
    console.log('用户信息:', userInfo)
    
    // 获取qrCode
    let qrCodeValue = randomCode // 默认使用随机数作为qrCode
    
    try {
      const qrCodeResponse = await api.post('/api/Patient/get-qrcode', {
        patientId: auditForm.value.refundItem.patientId
      })
      
      if (qrCodeResponse.data && qrCodeResponse.data.qrCode) {
        qrCodeValue = qrCodeResponse.data.qrCode
        console.log('从HIS系统获取到qrCode:', qrCodeValue)
      } else {
        console.log('HIS系统未返回qrCode，使用默认值:', qrCodeValue)
      }
    } catch (qrError) {
      console.warn('获取qrCode失败，使用默认值:', qrError)
      // 继续使用默认的randomCode
    }
    
    // 准备统一接口参数
    const request = {
      patientId: auditForm.value.refundItem.patientId,
      refundPassword: encryptedPassword,
      modifier: userInfo.fullName || userInfo.username,
      modifierCardType: '08',
      modifierCardCode: auditForm.value.refundItem.idNumber || '',
      modifyTime: new Date().toISOString(),
      orgPassword: randomCode,
      verifyCode: randomCode, // 使用原始6位随机数
      qrCode: qrCodeValue, // 使用从HIS系统获取的qrCode或默认值
      refundBalance: detailPatientBalance.value || patientBalance.value || 0,
      userId: userInfo.username,
      userName: userInfo.fullName || userInfo.username,
      patName: auditForm.value.refundItem.patName,
      idNumber: auditForm.value.refundItem.idNumber
    }
    console.log('统一接口请求参数:', request)
    
    // 调用新的统一接口
    const response = await api.post('/api/RefundProcess/wait-for-his-refund', request)
    console.log('统一接口响应:', response.data)
    
    if (response.data && response.data.success) {
      console.log('HIS退费流程执行成功')
      
      // 更新数据库中的HIS退费状态
      try {
        const statusResponse = await api.post('/api/Refund/update-his-refund-status', {
          id: auditForm.value.refundItem.id,
          hisRefundStatus: 'waiting'
        })
        
        if (statusResponse.data && statusResponse.data.success) {
          console.log('数据库HIS退费状态更新成功')
          
          // 设置等待HIS退费状态为true
          auditForm.value.waitingHisRefund = true
          console.log('设置 waitingHisRefund 为 true')
          
          // 重新计算按钮禁用状态
          const buttonDisabled = auditLoading.value || 
            (auditForm.value.result === '1' && !auditForm.value.waitingHisRefund) || 
            (auditForm.value.result === '1' && patientBalance.value !== null && patientBalance.value <= 0)
          
          console.log('HIS退费后按钮禁用状态:', buttonDisabled)
          
          // 启动10分钟定时器并阻止页面离开
          startCountdownTimer()
          showToast('HIS退费密码设置成功，验证码已生成，现在可以确认通过。注意：10分钟内不能刷新或关闭页面！', 'success')
        } else {
          console.log('数据库HIS退费状态更新失败:', statusResponse.data?.message)
          showToast('数据库状态更新失败：' + (statusResponse.data?.message || '未知错误'), 'error')
          return
        }
      } catch (statusError) {
        console.error('更新数据库HIS退费状态失败:', statusError)
        showToast('更新数据库状态失败：' + (statusError.response?.data?.message || statusError.message || '网络错误'), 'error')
        return
      }
    } else {
      console.log('HIS退费流程执行失败:', response.data?.message)
      showToast('HIS退费流程执行失败：' + (response.data?.message || '未知错误'), 'error')
    }
  } catch (error) {
    console.error('等待HIS退费操作失败:', error)
    showToast('操作失败：' + (error.response?.data?.message || error.message || '网络错误'), 'error')
  }
  
  console.log('=== waitForHisRefund 结束 ===')
}

// 提交审核
const submitAudit = async () => {
  // 声明退费流水号变量
  let refundBalanceSn = null
  
  // 验证审核备注
  if (!auditForm.value.comment.trim()) {
    auditForm.value.showError = true
    return
  }
  
  // 如果是审核通过，验证实际退款金额
  if (auditForm.value.result === '1') {
    // 检查HIS系统余额是否为0
    if (patientBalance.value !== null && patientBalance.value <= 0) {
      showToast('HIS系统余额为0，无法确认通过审核', 'error')
      return
    }
    if (!auditForm.value.refundBalance || auditForm.value.refundBalance <= 0) {
      auditForm.value.showError = true
      return
    }
    if (auditForm.value.refundBalance > auditForm.value.refundItem.refundAmount) {
      showToast('实际退款金额不能超过申请金额', 'error')
      return
    }
    
    // 审核通过时的额外检查：查询实时余额和退费流水号
    try {
      // 1. 查询患者实时余额
      //showToast('正在查询患者实时余额...', 'info')
      const realTimeBalanceResponse = await api.get(`/api/refund/patient-balance/${auditForm.value.refundItem.patientId}`)
      
      let realTimeBalance = 0
      if (realTimeBalanceResponse.data && realTimeBalanceResponse.data.success && realTimeBalanceResponse.data.data) {
        realTimeBalance = realTimeBalanceResponse.data.data.balance
      }
      
      // 2. 检查实时余额是否大于0
      if (realTimeBalance > 0) {
        showToast('患者未完成HIS退款，请等待HIS完成退款再审核', 'warning')
        return
      }
      
      // 3. 查询退费流水号
      //showToast('正在查询退费流水号...', 'info')
      const currentBalance = patientBalance.value || 0
      const refundBalanceSnRequest = {
        patientId: auditForm.value.refundItem.patientId,
        refundBalance: currentBalance * -1 // 传入当前就诊卡余额的负值
      }
      
      const refundSnResponse = await api.post('/api/Patient/get-refund-balance-sn', refundBalanceSnRequest)
      
      // 4. 检查是否查询到退费流水号
      
      // 尝试多种可能的数据结构
      if (refundSnResponse.data) {
        if (refundSnResponse.data.refundBalanceSn) {
          // 直接在data中
          refundBalanceSn = refundSnResponse.data.refundBalanceSn
        } else if (refundSnResponse.data.data && refundSnResponse.data.data.refundBalanceSn) {
          // 嵌套在data.data中
          refundBalanceSn = refundSnResponse.data.data.refundBalanceSn
        } else if (refundSnResponse.data.success && refundSnResponse.data.data && refundSnResponse.data.data.refundBalanceSn) {
          // 标准格式：有success字段且嵌套在data.data中
          refundBalanceSn = refundSnResponse.data.data.refundBalanceSn
        }
      }
      
      if (!refundBalanceSn) {
        showToast('无法查询到退费流水号，不能完成审核', 'error')
        return
      }
      
      //showToast('退费流水号验证通过，继续执行审核', 'success')
      
    } catch (error) {
      console.error('实时余额或退费流水号查询失败:', error)
      showToast('查询失败：' + (error.response?.data?.message || error.message || '网络错误'), 'error')
      return
    }
  }
  
  // 开始执行审核提交逻辑
  auditLoading.value = true
  try {
    const auditData = {
      id: auditForm.value.refundItem.id,
      auditResult: auditForm.value.result,
      auditComment: auditForm.value.comment.trim(),
      refundBalance: auditForm.value.result === '1' ? auditForm.value.refundBalance : null,
      refundBalanceSn: auditForm.value.result === '1' ? refundBalanceSn : null
    }
    
    const response = await api.patch(`/api/refund/${auditForm.value.refundItem.id}/audit`, auditData)
    
    // 先重置状态，确保模态框可以正常关闭
    if (auditForm.value.result === '1') {
      clearCountdownTimer()
    }
    // 立即重置关键状态
    auditForm.value.preventPageLeave = false
    auditForm.value.waitingHisRefund = false
    
    // 然后关闭模态框
    if (auditModal) {
      auditModal.hide()
    }
    
    // 使用返回的数据更新界面，避免重新查询数据库
    if (response.data && response.data.data) {
      const updatedItem = response.data.data
      console.log('收到更新的数据:', updatedItem)
      
      // 在当前列表中找到对应项并更新
      const index = refundList.value.findIndex(item => item.id === updatedItem.id)
      if (index !== -1) {
        console.log('更新列表中的项目，索引:', index)
        refundList.value[index] = updatedItem
        // 强制触发响应式更新
        refundList.value = [...refundList.value]
      }
      
      // 如果当前选中的是这个项目，也更新选中项
      if (selectedItem.value && selectedItem.value?.id === updatedItem.id) {
        console.log('更新选中项目')
        selectedItem.value = updatedItem
      }
    } else {
      console.warn('未收到更新的数据:', response.data)
    }
    
    // 如果是审核通过，更新HIS退费状态为completed
    if (auditForm.value.result === '1') {
      try {
        const updateStatusRequest = {
          id: auditForm.value.refundItem.id,
          hisRefundStatus: 'completed'
        }
        
        const updateResponse = await api.post('/api/Refund/update-his-refund-status', updateStatusRequest)
        
        if (updateResponse.data && updateResponse.data.success) {
          console.log('HIS退费状态更新为completed成功')
        } else {
          console.warn('HIS退费状态更新失败:', updateResponse.data?.message || '未知错误')
        }
      } catch (updateError) {
        console.error('更新HIS退费状态异常:', updateError)
        // 不影响主流程，只记录错误
      }
    }
    
    // 显示成功消息
    const resultText = auditForm.value.result === '1' ? '通过' : '失败'
    //showToast(`审核${resultText}成功`, 'success')
    
  } catch (error) {
    console.error('审核失败:', error)
    const resultText = auditForm.value.result === '1' ? '通过' : '失败'
    
    // 检查服务器返回的错误信息
    if (error.response && error.response.data && error.response.data.message) {
      // 服务器返回的具体错误信息
      const serverMessage = error.response.data.message
      showToast(serverMessage, 'error')
    } else if (error.response && error.response.status) {
      // 根据HTTP状态码处理
      const status = error.response.status
      
      if (status === 404) {
        // 记录不存在
        showToast('退费申请不存在，请刷新页面', 'error')
        loadRefundList()
      } else {
        // 其他HTTP错误
        showToast(`审核${resultText}失败，服务器错误(${status})`, 'error')
      }
    } else {
      // 网络错误或其他错误
      showToast(`审核${resultText}失败，请检查网络连接`, 'error')
    }
  } finally {
    auditLoading.value = false
    
    // 确保完全重置审核表单状态
    auditForm.value.preventPageLeave = false
    auditForm.value.waitingHisRefund = false
    auditForm.value.countdownTimer = null
    auditForm.value.remainingTime = 0
    
    console.log('审核提交完成，所有状态已重置')
  }
}

// 分页处理
const handlePageChange = (page) => {
  if (page < 1 || page > Math.ceil(totalCount.value / pageSize.value)) {
    return
  }
  currentPage.value = page
  loadRefundList()
}

// 跳转到指定页面
const handleJumpToPage = () => {
  const page = parseInt(jumpToPage.value)
  const totalPages = Math.ceil(totalCount.value / pageSize.value)
  
  if (isNaN(page) || page < 1 || page > totalPages) {
    showToast('请输入有效的页码（1-' + totalPages + '）', 'warning')
    jumpToPage.value = ''
    return
  }
  
  jumpToPage.value = ''
  handlePageChange(page)
}

// 处理每页显示条数变化
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize
  currentPage.value = 1 // 重置到第一页
  jumpToPage.value = ''
  loadRefundList()
}

// 获取页码数组
const getPageNumbers = () => {
  const totalPages = Math.ceil(totalCount.value / pageSize.value)
  const pages = []
  const maxVisiblePages = 5
  
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2))
  let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1)
  
  // 调整起始页
  if (endPage - startPage + 1 < maxVisiblePages) {
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
}

// 预览附件
const previewAttachments = (item) => {
  if (item.attachments && item.attachments.length > 0) {
    // 设置当前附件列表
    currentAttachments.value = item.attachments
    currentImageIndex.value = 0
    previewImage(item.attachments[0])
  }
}

// 预览图片
const previewImage = async (attachment) => {
  // 如果是从缩略图点击进来的，需要设置当前附件列表和索引
  if (selectedItem.value && selectedItem.value?.attachments) {
    currentAttachments.value = selectedItem.value?.attachments
    currentImageIndex.value = selectedItem.value?.attachments.findIndex(att => att.id === attachment.id)
  }
  
  previewAttachment.value = attachment
  previewImageUrl.value = ''
  imageLoading.value = true
  imageRotation.value = 0 // 重置旋转角度
  imageScale.value = 1 // 重置缩放比例
  imagePosition.value = { x: 0, y: 0 } // 重置位置
  imageFocused.value = false // 重置聚焦状态
  
  if (attachmentModal) {
    attachmentModal.show()
  }
  
  // 动态加载图片
  const imageUrl = await loadImageData(attachment)
  if (imageUrl) {
    previewImageUrl.value = imageUrl
  }
  imageLoading.value = false
}

// 上一张图片
const previousImage = async () => {
  if (currentImageIndex.value > 0) {
    // 清理之前的图片URL资源
    if (previewImageUrl.value && previewImageUrl.value.startsWith('blob:')) {
      URL.revokeObjectURL(previewImageUrl.value)
    }
    
    currentImageIndex.value--
    const attachment = currentAttachments.value[currentImageIndex.value]
    previewAttachment.value = attachment
    previewImageUrl.value = ''
    imageLoading.value = true
    imageRotation.value = 0 // 重置旋转角度
    imageScale.value = 1 // 重置缩放比例
    imagePosition.value = { x: 0, y: 0 } // 重置位置
    imageFocused.value = false // 重置聚焦状态
    
    // 加载新图片
    const imageUrl = await loadImageData(attachment)
    if (imageUrl) {
      previewImageUrl.value = imageUrl
    }
    imageLoading.value = false
  }
}

// 下一张图片
const nextImage = async () => {
  if (currentImageIndex.value < currentAttachments.value.length - 1) {
    // 清理之前的图片URL资源
    if (previewImageUrl.value && previewImageUrl.value.startsWith('blob:')) {
      URL.revokeObjectURL(previewImageUrl.value)
    }
    
    currentImageIndex.value++
    const attachment = currentAttachments.value[currentImageIndex.value]
    previewAttachment.value = attachment
    previewImageUrl.value = ''
    imageLoading.value = true
    imageRotation.value = 0 // 重置旋转角度
    imageScale.value = 1 // 重置缩放比例
    imagePosition.value = { x: 0, y: 0 } // 重置位置
    imageFocused.value = false // 重置聚焦状态
    
    // 加载新图片
    const imageUrl = await loadImageData(attachment)
    if (imageUrl) {
      previewImageUrl.value = imageUrl
    }
    imageLoading.value = false
  }
}

// 跳转到指定图片
const goToImage = async (index) => {
  if (index >= 0 && index < currentAttachments.value.length && index !== currentImageIndex.value) {
    // 清理之前的图片URL资源
    if (previewImageUrl.value && previewImageUrl.value.startsWith('blob:')) {
      URL.revokeObjectURL(previewImageUrl.value)
    }
    
    currentImageIndex.value = index
    const attachment = currentAttachments.value[index]
    previewAttachment.value = attachment
    previewImageUrl.value = ''
    imageLoading.value = true
    imageRotation.value = 0 // 重置旋转角度
    imageScale.value = 1 // 重置缩放比例
    imagePosition.value = { x: 0, y: 0 } // 重置位置
    imageFocused.value = false // 重置聚焦状态
    
    // 加载新图片
    const imageUrl = await loadImageData(attachment)
    if (imageUrl) {
      previewImageUrl.value = imageUrl
    }
    imageLoading.value = false
  }
}

// 旋转图片
const rotateImage = (angle) => {
  imageRotation.value = imageRotation.value + angle
}

// 重置旋转
const resetRotation = () => {
  imageRotation.value = 0
}

// 缩放图片
const zoomImage = (delta) => {
  const newScale = imageScale.value + delta
  // 限制缩放范围在0.1到5之间
  if (newScale >= 0.1 && newScale <= 5) {
    imageScale.value = newScale
  }
}

// 重置缩放
const resetZoom = () => {
  imageScale.value = 1
}

// 开始拖拽
const startDrag = (event) => {
  isDragging.value = true
  dragStart.value = {
    x: event.clientX - imagePosition.value.x,
    y: event.clientY - imagePosition.value.y
  }
  event.preventDefault()
}

// 拖拽中
const onDrag = (event) => {
  if (isDragging.value) {
    imagePosition.value = {
      x: event.clientX - dragStart.value.x,
      y: event.clientY - dragStart.value.y
    }
  }
}

// 结束拖拽
const endDrag = () => {
  isDragging.value = false
}

// 重置位置
const resetPosition = () => {
  imagePosition.value = { x: 0, y: 0 }
}

// 处理图片点击聚焦
const focusImage = () => {
  imageFocused.value = true
  console.log('图片已聚焦，可以使用滚轮缩放')
}

// 处理鼠标滚轮缩放
const handleImageWheel = (event) => {
  // 只有在图片被聚焦时才响应滚轮事件
  if (!imageFocused.value) {
    return
  }
  
  event.preventDefault()
  event.stopPropagation()
  
  // 获取滚轮方向
  const delta = event.deltaY > 0 ? -0.1 : 0.1
  
  // 计算新的缩放比例
  const newScale = imageScale.value + delta
  
  // 限制缩放范围在0.1到5之间
  if (newScale >= 0.1 && newScale <= 5) {
    imageScale.value = newScale
    console.log('滚轮缩放:', imageScale.value.toFixed(2))
  }
}

// 获取图片预览URL - 由于API是POST请求，需要动态获取
const getImagePreviewUrl = (attachment) => {
  // 返回一个占位符，实际图片将通过loadImageData方法加载
  return attachment.filePaths ? 'loading' : ''
}

// 加载图片数据
const loadImageData = async (attachment) => {
  try {
    const response = await api.post('/api/File/get-by-path', {
      path: attachment.filePaths
    }, {
      responseType: 'blob'
    })
    
    // 创建blob URL
    const imageUrl = URL.createObjectURL(response.data)
    return imageUrl
  } catch (error) {
    console.error('加载图片失败:', error)
    return null
  }
}

// 加载缩略图
const loadThumbnail = async (attachment) => {
  if (!attachment.filePaths) return
  
  // 设置加载状态
  thumbnailLoading.value[attachment.id] = true
  
  try {
    const response = await api.post('/api/File/get-by-path', {
      path: attachment.filePaths
    }, {
      responseType: 'blob'
    })
    
    // 创建blob URL
    const imageUrl = URL.createObjectURL(response.data)
    thumbnailUrls.value[attachment.id] = imageUrl
    
  } catch (error) {
    console.error('加载缩略图失败:', error)
    // 加载失败时不设置URL，会显示默认图标
  } finally {
    thumbnailLoading.value[attachment.id] = false
  }
}

// 处理缩略图加载错误
const handleThumbnailError = (attachmentId) => {
  // 清除失败的URL
  if (thumbnailUrls.value[attachmentId]) {
    URL.revokeObjectURL(thumbnailUrls.value[attachmentId])
    delete thumbnailUrls.value[attachmentId]
  }
}

// 清理预览图片资源
const cleanupPreviewImage = () => {
  if (previewImageUrl.value && previewImageUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(previewImageUrl.value)
  }
  previewImageUrl.value = ''
  previewAttachment.value = null
  imageLoading.value = false
  currentAttachments.value = []
  currentImageIndex.value = 0
  imageRotation.value = 0
  imageScale.value = 1
  imagePosition.value = { x: 0, y: 0 }
  imageFocused.value = false
}

// 清理所有缩略图资源
const cleanupThumbnails = () => {
  Object.values(thumbnailUrls.value).forEach(url => {
    if (url && url.startsWith('blob:')) {
      URL.revokeObjectURL(url)
    }
  })
  thumbnailUrls.value = {}
  thumbnailLoading.value = {}
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = ''
}

// 下载附件
const downloadAttachment = async (attachment) => {
  try {
    const response = await api.post('/api/file/download', {
      fileId: attachment.fileId
    }, {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `${attachment.attachName}.jpg`)
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)
    
  } catch (error) {
    console.error('下载附件失败:', error)
    showToast('下载附件失败', 'error')
  }
}

// 加载审核字典
const loadAuditDict = async (dictId = 5) => {
  try {
    const response = await api.post('/api/Dict/get-by-dict-id', {
      dictId: dictId
    })
    
    auditDictList.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('加载审核字典失败:', error)
    auditDictList.value = []
  }
}

// 打印相关方法
const openPrintSettings = () => {
  // 重置打印设置
  printSettings.value = {
    selectedImages: new Set(),
    paperSize: 'A4',
    orientation: 'portrait',
    margin: '10',
    imagesPerPage: 1,
    fitToPage: true,
    showPrintPreview: false
  }
  
  // 默认选中所有图片
  if (currentAttachments.value && currentAttachments.value.length > 0) {
    currentAttachments.value.forEach((_, index) => {
      printSettings.value.selectedImages.add(index)
    })
  }
  
  if (printSettingsModal) {
    printSettingsModal.show()
  }
}

const toggleImageSelection = (index) => {
  if (printSettings.value.selectedImages.has(index)) {
    printSettings.value.selectedImages.delete(index)
  } else {
    printSettings.value.selectedImages.add(index)
  }
}

const selectAllImages = () => {
  printSettings.value.selectedImages.clear()
  currentAttachments.value.forEach((_, index) => {
    printSettings.value.selectedImages.add(index)
  })
}

const deselectAllImages = () => {
  printSettings.value.selectedImages.clear()
}

const generatePrintPreview = async () => {
  if (printSettings.value.selectedImages.size === 0) {
    showToast('请至少选择一张图片进行打印', 'warning')
    return
  }
  
  printLoading.value = true
  printPreviewImages.value = []
  
  try {
    // 获取选中的图片数据
    const selectedIndexes = Array.from(printSettings.value.selectedImages).sort((a, b) => a - b)
    const imagePromises = selectedIndexes.map(async (index) => {
      const attachment = currentAttachments.value[index]
      const imageUrl = await loadImageData(attachment)
      return {
        url: imageUrl,
        name: attachment.attachName,
        index: index
      }
    })
    
    const images = await Promise.all(imagePromises)
    printPreviewImages.value = images.filter(img => img.url) // 过滤掉加载失败的图片
    
    if (printPreviewImages.value.length === 0) {
      showToast('所选图片加载失败，无法生成预览', 'error')
      return
    }
    
    // 关闭设置模态框，打开预览模态框
    if (printSettingsModal) {
      printSettingsModal.hide()
    }
    
    setTimeout(() => {
      if (printPreviewModal) {
        printPreviewModal.show()
      }
    }, 300)
    
  } catch (error) {
    console.error('生成打印预览失败:', error)
    showToast('生成打印预览失败', 'error')
  } finally {
    printLoading.value = false
  }
}

const executePrint = () => {
  if (printPreviewImages.value.length === 0) {
    showToast('没有可打印的图片', 'warning')
    return
  }
  
  // 创建打印窗口
  const printWindow = window.open('', '_blank')
  
  // 构建打印页面HTML
  let printHTML = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>附件打印</title>
      <style>
        @page {
          size: ${printSettings.value.paperSize} ${printSettings.value.orientation};
          margin: ${printSettings.value.margin}mm;
        }
        body {
          margin: 0;
          padding: 0;
          font-family: Arial, sans-serif;
        }
        .page {
          page-break-after: always;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          box-sizing: border-box;
        }
        .page:last-child {
          page-break-after: avoid;
        }
        .image-container {
          text-align: center;
          margin-bottom: 20px;
          width: 100%;
        }
        .print-image {
          max-width: 100%;
          max-height: ${printSettings.value.fitToPage ? '80vh' : 'auto'};
          object-fit: contain;
          border: 1px solid #ddd;
          box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .image-title {
          margin-top: 10px;
          font-size: 14px;
          color: #666;
          word-break: break-all;
        }
        .print-header {
          text-align: center;
          margin-bottom: 20px;
          padding-bottom: 10px;
          border-bottom: 2px solid #007bff;
        }
        .print-title {
          font-size: 18px;
          font-weight: bold;
          color: #333;
          margin: 0;
        }
        .print-info {
          font-size: 12px;
          color: #666;
          margin: 5px 0 0 0;
        }
      </style>
    </head>
    <body>
  `
  
  // 根据每页图片数量分组
  const imagesPerPage = parseInt(printSettings.value.imagesPerPage)
  const totalPages = Math.ceil(printPreviewImages.value.length / imagesPerPage)
  
  for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {
    const startIndex = pageIndex * imagesPerPage
    const endIndex = Math.min(startIndex + imagesPerPage, printPreviewImages.value.length)
    const pageImages = printPreviewImages.value.slice(startIndex, endIndex)
    
    printHTML += `
      <div class="page">
        <div class="print-header">
          <h1 class="print-title">退款申请附件</h1>
          <p class="print-info">申请ID: ${selectedItem.value?.id || ''} | 就诊人: ${selectedItem.value?.patName || ''} | 打印时间: ${new Date().toLocaleString()}</p>
          <p class="print-info">第 ${pageIndex + 1} 页，共 ${totalPages} 页</p>
        </div>
    `
    
    pageImages.forEach(image => {
      printHTML += `
        <div class="image-container">
          <img src="${image.url}" alt="${image.name}" class="print-image">
          <div class="image-title">${image.name}</div>
        </div>
      `
    })
    
    printHTML += `</div>`
  }
  
  printHTML += `
    </body>
    </html>
  `
  
  // 写入打印窗口并打印
  printWindow.document.write(printHTML)
  printWindow.document.close()
  
  // 等待图片加载完成后打印
  printWindow.onload = () => {
    setTimeout(() => {
      printWindow.print()
      printWindow.close()
    }, 1000)
  }
  
  // 关闭预览模态框
  if (printPreviewModal) {
    printPreviewModal.hide()
  }
  
  showToast('正在准备打印...', 'info')
}

const closePrintPreview = () => {
  // 清理预览图片资源
  printPreviewImages.value.forEach(image => {
    if (image.url && image.url.startsWith('blob:')) {
      URL.revokeObjectURL(image.url)
    }
  })
  printPreviewImages.value = []
  
  if (printPreviewModal) {
    printPreviewModal.hide()
  }
}

// 显示Toast消息
const showToast = (message, type = 'info') => {
  // 控制台日志
  console.log(`Toast [${type}]: ${message}`)
  
  // 使用浏览器原生alert弹窗
  alert(message)
  
  // 如果需要更好的UI体验，可以使用Bootstrap的Toast组件
  // 这里先用简单的alert确保用户能看到提示
}

// 启动倒计时定时器
const startCountdownTimer = () => {
  // 设置10分钟（600秒）
  auditForm.value.remainingTime = 600
  auditForm.value.preventPageLeave = true
  
  // 设置模态框为不可关闭状态
  const auditModalElement = document.getElementById('auditModal')
  if (auditModalElement) {
    auditModalElement.setAttribute('data-bs-backdrop', 'static')
    auditModalElement.setAttribute('data-bs-keyboard', 'false')
  }
  
  // 清除之前的定时器（如果存在）
  if (auditForm.value.countdownTimer) {
    clearInterval(auditForm.value.countdownTimer)
  }
  
  // 启动新的定时器
  auditForm.value.countdownTimer = setInterval(() => {
    auditForm.value.remainingTime--
    
    // 时间到了自动清除
    if (auditForm.value.remainingTime <= 0) {
      clearCountdownTimer()
      showToast('10分钟时间已到，页面限制已解除', 'info')
    }
  }, 1000)
  
  console.log('已启动10分钟倒计时，页面离开限制已激活')
}

// 清除倒计时定时器
const clearCountdownTimer = () => {
  if (auditForm.value.countdownTimer) {
    clearInterval(auditForm.value.countdownTimer)
    auditForm.value.countdownTimer = null
  }
  auditForm.value.remainingTime = 0
  auditForm.value.preventPageLeave = false
  
  // 恢复模态框的正常关闭功能
  const auditModalElement = document.getElementById('auditModal')
  if (auditModalElement) {
    auditModalElement.removeAttribute('data-bs-backdrop')
    auditModalElement.removeAttribute('data-bs-keyboard')
  }
  
  console.log('倒计时已清除，页面离开限制已解除')
}

// 银行卡验证方法
const validateBankCardInfo = (cardNumber, bankName) => {
  console.log('开始验证银行卡信息:', { cardNumber, bankName })
  
  if (!cardNumber || !bankName) {
    console.log('银行卡号或银行名称为空')
    bankValidation.value = {
      isValid: false,
      cardNumberValid: false,
      bankNameValid: false,
      bankMatch: false,
      detectedBank: null,
      standardizedBankName: null,
      errors: ['银行卡号和银行名称不能为空']
    }
    return bankValidation.value
  }
  
  try {
    console.log('调用validateBankCard函数')
    const result = validateBankCard(cardNumber, bankName)
    console.log('验证结果:', result)
    
    // 适配增强版验证器的返回格式
    bankValidation.value = {
      isValid: result.valid || false,
      cardNumberValid: result.luhnValid || false,
      bankNameValid: !!result.standardBankName,
      bankMatch: result.bankMatched || false,
      detectedBank: result.bankInfo ? result.bankInfo.name : null,
      standardizedBankName: result.standardBankName || null,
      errors: result.valid ? [] : [result.message || '验证失败']
    }
    
    console.log('更新后的bankValidation:', bankValidation.value)
    return bankValidation.value
  } catch (error) {
    console.error('银行卡验证失败:', error)
    bankValidation.value = {
      isValid: false,
      cardNumberValid: false,
      bankNameValid: false,
      bankMatch: false,
      detectedBank: null,
      standardizedBankName: null,
      errors: ['验证过程中发生错误: ' + error.message]
    }
    return bankValidation.value
  }
}

// 监听选中项变化，自动验证银行卡信息
watch(
  () => selectedItem.value,
  (newItem) => {
    if (newItem) {
      // 根据退款类型选择对应的银行信息进行验证
      let cardNumber, bankName
      if (newItem.refundTypeId === '5') {
        // 代办人退款，使用代办人银行信息
        cardNumber = newItem.publicAgentRefundBankCardNo
        bankName = newItem.publicAgentRefundBankName
      } else {
        // 本人退款，使用本人银行信息
        cardNumber = newItem.refundBankCardNo
        bankName = newItem.refundBankName
      }
      
      if (cardNumber && bankName) {
        validateBankCardInfo(cardNumber, bankName)
      } else {
        // 重置验证状态
        bankValidation.value = {
          isValid: false,
          cardNumberValid: false,
          bankNameValid: false,
          bankMatch: false,
          detectedBank: null,
          standardizedBankName: null,
          errors: []
        }
      }
    } else {
      // 重置验证状态
      bankValidation.value = {
        isValid: false,
        cardNumberValid: false,
        bankNameValid: false,
        bankMatch: false,
        detectedBank: null,
        standardizedBankName: null,
        errors: []
      }
    }
  },
  { immediate: true }
)

// 页面离开前的确认
const handleBeforeUnload = (event) => {
  if (auditForm.value.preventPageLeave) {
    const message = '您正在等待HIS退费确认，10分钟内不能离开页面！'
    event.preventDefault()
    event.returnValue = message
    return message
  }
}

// 格式化剩余时间显示
const formatRemainingTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 处理详情模态框关闭
const handleModalClose = () => {
  if (detailModal) {
    detailModal.hide()
  }
}

// 处理审核模态框关闭
const handleAuditModalClose = () => {
  if (auditForm.value.preventPageLeave) {
    showToast('正在等待HIS退费确认，不能关闭审核页面！', 'error')
    return
  }
  if (auditModal) {
    auditModal.hide()
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 初始化模态框
  const modalElement = document.getElementById('detailModal')
  if (modalElement) {
    detailModal = new Modal(modalElement)
    // 监听详情模态框关闭事件，清理缩略图资源
    modalElement.addEventListener('hidden.bs.modal', cleanupThumbnails)
  }
  
  const auditModalElement = document.getElementById('auditModal')
  if (auditModalElement) {
    auditModal = new Modal(auditModalElement)
    // 监听审核模态框的隐藏事件，阻止在等待HIS退费时关闭
    auditModalElement.addEventListener('hide.bs.modal', (event) => {
      if (auditForm.value.preventPageLeave) {
        event.preventDefault()
        showToast('正在等待HIS退费确认，不能关闭审核页面！', 'error')
      }
    })
  }
  
  const attachmentModalElement = document.getElementById('attachmentModal')
  if (attachmentModalElement) {
    attachmentModal = new Modal(attachmentModalElement)
    // 监听模态框关闭事件，清理资源
    attachmentModalElement.addEventListener('hidden.bs.modal', cleanupPreviewImage)
  }
  
  // 初始化打印设置模态框
  const printSettingsModalElement = document.getElementById('printSettingsModal')
  if (printSettingsModalElement) {
    printSettingsModal = new Modal(printSettingsModalElement)
  }
  
  // 初始化打印预览模态框
  const printPreviewModalElement = document.getElementById('printPreviewModal')
  if (printPreviewModalElement) {
    printPreviewModal = new Modal(printPreviewModalElement)
  }
  
  // 添加键盘事件监听器
  document.addEventListener('keydown', handleKeydown)
  
  // 添加页面离开监听器
  window.addEventListener('beforeunload', handleBeforeUnload)
  
  // 加载初始数据
  loadRefundList()
})

// 组件卸载时清理
onUnmounted(() => {
  // 移除键盘事件监听器
  document.removeEventListener('keydown', handleKeydown)
  
  // 移除页面离开监听器
  window.removeEventListener('beforeunload', handleBeforeUnload)
  
  // 清除定时器
  clearCountdownTimer()
  
  // 清理所有资源
  cleanupThumbnails()
  cleanupPreviewImage()
})
</script>

<style scoped>
.refund-management {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.card {
  border: none;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
}

.table th {
  font-weight: 600;
  color: #495057;
  border-top: none;
}

.table td {
  vertical-align: middle;
}

.btn-group-sm .btn {
  padding: 0.25rem 0.5rem;
}

.text-truncate {
  cursor: help;
}

.modal-body .form-label {
  color: #6c757d;
  font-size: 0.875rem;
  margin-bottom: 0.25rem;
}

.modal-body .form-control-plaintext {
  padding: 0.375rem 0;
  margin-bottom: 0;
  font-size: 0.875rem;
  line-height: 1.5;
  color: #212529;
  background-color: transparent;
  border: solid transparent;
  border-width: 1px 0;
}

.table-responsive {
  overflow-x: auto;
}

.btn-group .btn {
  margin-right: 5px;
}

.btn-group .btn:last-child {
  margin-right: 0;
}

.modal-body {
  max-height: 70vh;
  overflow-y: auto;
}

/* 详情模态框样式优化 */
.detail-modal-content {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.detail-modal-header {
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 1.25rem 1.5rem;
}

.detail-modal-title {
  font-weight: 600;
  margin: 0;
}

.detail-modal-body {
  padding: 1.5rem;
}

/* 模态框中卡片间距调整 */
.detail-modal-body .card {
  margin-bottom: 1.5rem;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.detail-modal-body .card:first-child {
  margin-top: 0;
}

.detail-modal-body .card:last-child {
  margin-bottom: 0;
}

.detail-modal-body .card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #495057;
  padding: 0.75rem 1rem;
}

.attachment-item {
  display: inline-block;
  margin: 5px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: background-color 0.3s;
}

.attachment-item:hover {
  background-color: #e9ecef;
}

.attachment-thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 5px;
}

.attachment-name {
  font-size: 12px;
  text-align: center;
  word-break: break-all;
  max-width: 80px;
}

.loading-placeholder {
  width: 80px;
  height: 80px;
  background-color: #f8f9fa;
  border: 1px dashed #dee2e6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 5px;
}

.preview-image {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
}

.image-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

/* 图片轮播相关样式 */
.image-carousel {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.carousel-nav {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s, opacity 0.3s;
  z-index: 10;
}

.carousel-nav:hover {
  background: rgba(0, 0, 0, 0.7);
}

.carousel-nav:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.carousel-nav.prev {
  left: 10px;
}

.carousel-nav.next {
  right: 10px;
}

.carousel-indicators {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 15px;
}

.indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.3);
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.indicator.active {
  background: #007bff;
}

.indicator:hover {
  background: rgba(0, 123, 255, 0.7);
}

.carousel-info {
  text-align: center;
  margin-bottom: 10px;
  color: #6c757d;
  font-size: 14px;
}

/* 分页组件美化样式 */
.pagination {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.pagination .page-link {
  border: none;
  color: #6c757d;
  padding: 0.75rem 1rem;
  transition: all 0.3s ease;
  position: relative;
}

.pagination .page-link:hover {
  background-color: #e9ecef;
  color: #495057;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination .page-item.active .page-link {
  background: linear-gradient(135deg, #007bff, #0056b3);
  border-color: #007bff;
  color: white;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.pagination .page-item.disabled .page-link {
  color: #adb5bd;
  background-color: #f8f9fa;
}

.form-select-sm {
  border-radius: 6px;
  border: 1px solid #ced4da;
  transition: all 0.3s ease;
}

.form-select-sm:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-control-sm {
  border-radius: 6px;
  border: 1px solid #ced4da;
  transition: all 0.3s ease;
}

.form-control-sm:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.btn-outline-primary {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.btn-outline-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

/* 分页信息区域美化 */
.text-muted {
  font-size: 0.9rem;
}

.text-muted i {
  color: #007bff;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .pagination {
    font-size: 0.875rem;
  }
  
  .pagination .page-link {
    padding: 0.5rem 0.75rem;
  }
  
  .form-select-sm, .form-control-sm {
    font-size: 0.875rem;
  }
}

/* 申请类型和审核状态徽章样式增强 */
.status-badge-large {
  font-size: 0.9rem !important;
  padding: 0.5rem 0.8rem !important;
  font-weight: 600 !important;
  letter-spacing: 0.5px;
  border-radius: 6px !important;
  min-width: 80px;
  display: inline-block;
  text-align: center;
}

.type-badge-large {
  font-size: 0.9rem !important;
  padding: 0.5rem 0.8rem !important;
  font-weight: 600 !important;
  letter-spacing: 0.5px;
  border-radius: 6px !important;
  min-width: 80px;
  display: inline-block;
  text-align: center;
}

/* 表格中的申请类型和审核状态列样式 */
table td .status-badge-large,
table td .type-badge-large {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

table td .status-badge-large:hover,
table td .type-badge-large:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 增强不同状态的视觉效果 */
.status-badge-large.bg-warning {
  background: linear-gradient(135deg, #ffc107, #ffb300) !important;
  color: #212529 !important;
}

.status-badge-large.bg-success {
  background: linear-gradient(135deg, #28a745, #20c997) !important;
}

.status-badge-large.bg-danger {
  background: linear-gradient(135deg, #dc3545, #e74c3c) !important;
}

.type-badge-large.bg-primary {
  background: linear-gradient(135deg, #007bff, #0056b3) !important;
}

.type-badge-large.bg-info {
  background: linear-gradient(135deg, #17a2b8, #138496) !important;
}

/* 申请退款金额样式增强 */
.refund-amount-large {
  font-size: 1.1rem !important;
  font-weight: 700 !important;
  line-height: 1.4;
  margin-bottom: 0.25rem;
}

.refund-amount-medium {
  font-size: 0.95rem !important;
  font-weight: 600 !important;
  line-height: 1.3;
  margin-bottom: 0.1rem;
}

.amount-highlight {
  font-size: 1.2em !important;
  font-weight: 800 !important;
  font-family: 'Courier New', 'Monaco', monospace;
  letter-spacing: 0.5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  padding: 0.1rem 0.3rem;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: inline-block;
  min-width: 80px;
  text-align: center;
}

/* 不同状态下的金额高亮效果 */
.text-success .amount-highlight {
  background: rgba(40, 167, 69, 0.1) !important;
  border-color: rgba(40, 167, 69, 0.3) !important;
  color: #155724 !important;
}

.text-danger .amount-highlight {
  background: rgba(220, 53, 69, 0.1) !important;
  border-color: rgba(220, 53, 69, 0.3) !important;
  color: #721c24 !important;
}

/* 悬停效果 */
.amount-highlight:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

/* 表格行悬停时的金额突出效果 */
table tbody tr:hover .amount-highlight {
  transform: scale(1.02);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  transition: all 0.2s ease;
}

/* 操作按钮美化样式 */
.action-buttons-container {
  display: flex;
  gap: 0.25rem;
  justify-content: center;
  align-items: center;
}

.action-btn {
  position: relative;
  min-width: 2.5rem;
  height: 2.5rem;
  border-radius: 0.5rem;
  border-width: 2px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.action-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s;
}

.action-btn:hover::before {
  left: 100%;
}

.action-icon {
  font-size: 1.1rem;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
}

/* 查看按钮样式 */
.action-btn-view {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  color: white;
}

.action-btn-view:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  border-color: #5a6fd8;
  color: white;
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.action-btn-view:hover .action-icon {
  transform: scale(1.2) rotate(5deg);
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

/* 审核通过按钮样式 */
.action-btn-approve {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  border-color: #11998e;
  color: white;
}

.action-btn-approve:hover {
  background: linear-gradient(135deg, #0e8078 0%, #2dd865 100%);
  border-color: #0e8078;
  color: white;
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 25px rgba(17, 153, 142, 0.4);
}

.action-btn-approve:hover .action-icon {
  transform: scale(1.3) rotate(360deg);
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

/* 审核失败按钮样式 */
.action-btn-reject {
  background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
  border-color: #ff416c;
  color: white;
}

.action-btn-reject:hover {
  background: linear-gradient(135deg, #e73c5e 0%, #e7431f 100%);
  border-color: #e73c5e;
  color: white;
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 25px rgba(255, 65, 108, 0.4);
}

.action-btn-reject:hover .action-icon {
  transform: scale(1.2) rotate(-10deg);
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

/* 按钮激活状态 */
.action-btn:active {
  transform: translateY(0) scale(0.95);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 按钮禁用状态 */
.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-btn:disabled:hover {
  transform: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 表格行悬停时的按钮效果 */
tr:hover .action-btn {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 按钮组动画 */
.action-buttons-container:hover .action-btn:not(:hover) {
  opacity: 0.7;
  transform: scale(0.95);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .action-btn {
    min-width: 2.2rem;
    height: 2.2rem;
  }
  
  .action-icon {
    font-size: 1rem;
  }
  
  .action-buttons-container {
    gap: 0.2rem;
  }
  
  /* 移动端表格优化 */
  .table-responsive-wrapper {
    margin: -1rem;
    padding: 1rem;
  }
  
  .table-nowrap {
    white-space: nowrap;
  }
  
  .table th,
  .table td {
    padding: 0.5rem 0.25rem;
    font-size: 0.8rem;
  }
  
  .refund-amount-large {
    font-size: 0.75rem;
  }
  
  .amount-highlight {
    font-size: 0.8rem;
  }
}

@media (max-width: 576px) {
  .card-header {
    padding: 0.75rem;
  }
  
  .card-body {
    padding: 0.75rem;
  }
  
  .table th,
  .table td {
    padding: 0.375rem 0.2rem;
    font-size: 0.75rem;
  }
  
  .btn-group-sm .btn {
    padding: 0.2rem 0.3rem;
    font-size: 0.7rem;
  }
  
  .small {
    font-size: 0.7rem;
  }
}

/* 表格水平滚动优化 */
.table-responsive-wrapper {
  position: relative;
}

.table-responsive {
  border-radius: 0.375rem;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05);
}

.table-nowrap {
  min-width: 1200px;
}

.table-nowrap th,
.table-nowrap td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.table-nowrap th:first-child,
.table-nowrap td:first-child {
  position: sticky;
  left: 0;
  background: white;
  z-index: 10;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.table-nowrap th:last-child,
.table-nowrap td:last-child {
  position: sticky;
  right: 0;
  background: white;
  z-index: 10;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
}

/* 汇总卡片样式 */
.summary-card {
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}

.summary-card .card-header {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  color: white;
  border-bottom: none;
  padding: 1rem 1.5rem;
}

.summary-card .card-header h6 {
  font-weight: 600;
  margin: 0;
  font-size: 1.1rem;
}

.summary-card .card-body {
  padding: 1.5rem;
}

.summary-item {
  padding: 1rem;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.summary-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  border-color: #007bff;
}

.summary-label {
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.summary-value {
  font-size: 1.25rem;
  font-weight: 700;
  font-family: 'Courier New', 'Monaco', monospace;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.25rem;
}

.summary-value i {
  font-size: 1.1rem;
  opacity: 0.8;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .summary-card .card-body {
    padding: 1rem;
  }
  
  .summary-item {
    padding: 0.75rem;
    margin-bottom: 0.75rem;
  }
  
  .summary-value {
    font-size: 1.1rem;
  }
  
  .summary-label {
    font-size: 0.8rem;
  }
}

@media (max-width: 576px) {
  .summary-card .card-header {
    padding: 0.75rem 1rem;
  }
  
  .summary-card .card-header h6 {
    font-size: 1rem;
  }
  
  .summary-item {
    padding: 0.5rem;
  }
  
  .summary-value {
    font-size: 1rem;
    flex-direction: column;
    gap: 0.1rem;
  }
  
  .summary-label {
    font-size: 0.75rem;
  }
}

/* 打印预览样式 */
.print-preview-container {
  background-color: #f8f9fa;
  padding: 20px;
}

.print-preview-page {
  background: white;
  border: 1px solid #ddd;
  margin-bottom: 20px;
}

.page-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
}

.print-image-container {
  border: 1px dashed #ccc;
  margin: 2px;
}

.print-image {
  border-radius: 4px;
}

.image-caption {
  font-size: 0.75rem;
  color: #6c757d;
}

/* 选择状态样式 */
.border-success {
  border-color: #198754 !important;
}

/* 打印设置表单样式 */
.form-check-label {
  cursor: pointer;
}

.form-check-input:checked {
  background-color: #198754;
  border-color: #198754;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .print-preview-page {
    transform: scale(0.7);
    transform-origin: top center;
  }
}
</style>